package com.firefightingiot.firefightingiot.web.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.cloudapi.sdk.model.ApiResponse;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.firefightingiot.firefightingiot.common.base.BaseService;
import com.firefightingiot.firefightingiot.common.utils.ByteUtil;
import com.firefightingiot.firefightingiot.common.utils.Dict;
import com.firefightingiot.firefightingiot.common.utils.appkit.ConfigKit;
import com.firefightingiot.firefightingiot.common.utils.appkit.FirefightingiotKit;
import com.firefightingiot.firefightingiot.config.dahua.DaHua;
import com.firefightingiot.firefightingiot.model.*;
import com.firefightingiot.firefightingiot.support.Rtmp.IoTApiClientBuilderParams;
import com.firefightingiot.firefightingiot.support.Rtmp.IoTApiRequest;
import com.firefightingiot.firefightingiot.support.Rtmp.SyncApiClient;
import com.firefightingiot.firefightingiot.support.model.RespEntity;
import com.firefightingiot.firefightingiot.support.mybatisplus.QueryWrapper;
import com.firefightingiot.firefightingiot.support.utils.DayUtil;
import com.firefightingiot.firefightingiot.support.utils.MyLogger;
import com.firefightingiot.firefightingiot.support.utils.hikvision.HikvisionInterfaceCall;
import com.firefightingiot.firefightingiot.support.utils.requestutil.HttpRequestUtil;
import com.firefightingiot.firefightingiot.web.domain.NormalBigItemsDo;
import com.firefightingiot.firefightingiot.web.domain.NormalSmallItemsDo;
import com.firefightingiot.firefightingiot.web.mapper.*;
import com.firefightingiot.firefightingiot.web.mapper.alarmtoday.DeviceAlarmLogAllTodayMapper;
import com.firefightingiot.firefightingiot.web.mapper.alarmtoday.DeviceAlarmLogAutoNetworkTodayMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
@Slf4j
public class DeviceService extends BaseService {

    @Resource
    public MyLogger logger;

    @Resource
    private DeviceBusinessMapper deviceBusinessMapper;
    @Resource
    private DeviceImgMapper deviceImgMapper;
    @Resource
    private DeviceNormalItemsMapper deviceNormalItemsMapper;
    @Resource
    private DeviceNormalLogMapper deviceNormalLogMapper;
    @Resource
    private DeviceTypeMapper deviceTypeMapper;
    @Resource
    private DeviceAlarmLogMapper deviceAlarmLogMapper;
    @Resource
    private DeviceAlarmLogImgMapper deviceAlarmLogImgMapper;
    @Resource
    NormalService normalService;
    @Resource
    ItemLogFieldMappingMapper itemLogFieldMappingMapper;
    @Resource
    private DeviceBusinessVideoplayAddrMapper deviceBusinessVideoplayAddrMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private DeviceWeChatMapper deviceWeChatMapper;
    @Resource
    DeviceAlarmLogAllTodayMapper deviceAlarmLogAllTodayMapper;
    @Resource
    IotSystemMapper iotSystemMapper;
    @Resource
    ChainofcvidenceUploadFileMapper chainofcvidenceUploadFileMapper;
    @Resource
    AsyncService asyncService;
    @Resource
    private DaHua daHua;
    @Resource
    private UltrasonicDeviceMapper ultrasonicDeviceMapper;
    @Resource
    private DeviceAlarmLogAutoNetworkTodayMapper deviceAlarmLogAutoNetworkTodayMapper;
    @Resource
    private DeviceChannelMapper deviceChannelMapper;
    @Resource
    private DeviceCameraBindingMapper deviceCameraBindingMapper;
    @Resource
    private DeviceSwitchService deviceSwitchService;
    @Resource
    private DeviceSwitchMapper deviceSwitchMapper;
    @Resource
    private DeviceBusinessChildrenMapper deviceBusinessChildrenMapper;
    @Resource
    private WaterColumnBoxDataMapper waterColumnBoxDataMapper;
    @Resource
    private WaterColumnBoxDataLogMapper waterColumnBoxDataLogMapper;
    @Resource
    private SosAddressBookMapper sosAddressBookMapper;
    @Resource
    private DeviceVideoPlayTimeMapper deviceVideoPlayTimeMapper;
    @Resource
    private GasFireExtinguishingDataMapper gasFireExtinguishingDataMapper;
    private static final char[] DIGITS
            = {'0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    public static final String toHex(byte[] data) {
        final StringBuffer sb = new StringBuffer(data.length * 2);
        for (int i = 0; i < data.length; i++) {
            sb.append(DIGITS[(data[i] >>> 4) & 0x0F]);
            sb.append(DIGITS[data[i] & 0x0F]);
        }
        return sb.toString();
    }

    public String save(JSONObject jsonParam) throws Exception {
        String msg = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        DeviceBusiness deviceBusiness = new DeviceBusiness();
        if (jsonParam.getStr("deviceClassify").equals("2")) {
            if (jsonParam.getStr("deviceType").equals("2") || jsonParam.getStr("deviceType").equals("1")  ) {
                deviceBusiness.setWaterattr("2");
            } else {
                deviceBusiness.setWaterattr("1");
            }
        }
        String uuid = "";
        if(StrUtil.isNotBlank(jsonParam.getStr("id"))){
            uuid = jsonParam.getStr("id");
            deviceBusiness.setCurrentstate(jsonParam.getStr("currentstate"));
            deviceBusiness.setNormalUpdateTime(jsonParam.getStr("normalUpdateTime"));
            deviceImgMapper.delete(new QueryWrapper<DeviceImg>().eq("device_id",jsonParam.getStr("id")));
        }else{
            uuid = UUID.randomUUID().toString();
            Date createtime = new Date();
            jsonParam.put("createtime",createtime);
            deviceBusiness.setCreatetime(createtime);
            jsonParam.put("id",uuid);
            deviceBusiness.setCurrentstate("3");
            deviceBusiness.setNormalUpdateTime(DateUtil.now());
            JSONObject json = new JSONObject();
            json.put("homeId",uuid);
            json.put("type",1);
            json.put("orgId",jsonParam.getStr("orgId"));
            json.put("count",5);
            makeDataForToken(json, "communicationJava", "config", "addOrUpdate", "communication");
            json.put("type",2);
            makeDataForToken(json, "communicationJava", "config", "addOrUpdate", "communication");
        }
        deviceBusiness.setProductKey(jsonParam.getStr("productKey"));
        deviceBusiness.setAllId(jsonParam.getStr("orgIds"));
        deviceBusiness.setId(jsonParam.getStr("id"));
        deviceBusiness.setDeviceClassify(jsonParam.getStr("deviceClassify"));
        deviceBusiness.setOrgId(jsonParam.getStr("orgId"));
        deviceBusiness.setBusinessId(jsonParam.getStr("businessId"));
        deviceBusiness.setBusinessName(jsonParam.getStr("businessName"));
        deviceBusiness.setName(jsonParam.getStr("name"));
        deviceBusiness.setNumber(jsonParam.getStr("number"));
        deviceBusiness.setInternetofthingsCardnum(jsonParam.getStr("internetofthingsCardnum"));
        deviceBusiness.setTransDeviceCode(jsonParam.getStr("transDeviceCode"));
        if ("6005".equals(jsonParam.getStr("productId"))){
            jsonParam.put("videoplayAddrs",daHua.getRtmp(jsonParam.getStr("number")));
        }
        deviceBusiness.setDeviceType(jsonParam.getStr("deviceType"));
        deviceBusiness.setInstalltime(jsonParam.getStr("installtime"));
        deviceBusiness.setPosition(jsonParam.getStr("position"));
        deviceBusiness.setLon(jsonParam.getStr("lon"));
        deviceBusiness.setLat(jsonParam.getStr("lat"));
        deviceBusiness.setProductId(jsonParam.getStr("productId"));
        deviceBusiness.setSpec(jsonParam.getStr("spec"));
        deviceBusiness.setAlarmPhone(jsonParam.getStr("alarmPhone"));
        deviceBusiness.setInstallperson(jsonParam.getStr("installperson"));
        deviceBusiness.setInstallpersonPhone(jsonParam.getStr("installpersonPhone"));
        deviceBusiness.setRemark(jsonParam.getStr("remark"));
        deviceBusiness.setIp(jsonParam.getStr("ip"));
        deviceBusiness.setPost(jsonParam.getStr("post"));
        deviceBusiness.setUsername(jsonParam.getStr("username"));
        deviceBusiness.setPassword(jsonParam.getStr("password"));
        deviceBusiness.setChannelNumber(jsonParam.getStr("channelNumber"));
        deviceBusiness.setModel(jsonParam.getStr("model"));
        deviceBusiness.setPlatformId(jsonParam.getStr("platformId"));
        deviceBusiness.setFunction(jsonParam.getStr("function"));
        deviceBusiness.setVideoplayAddr(jsonParam.getStr("videoplayAddr"));
        deviceBusiness.setRfid(jsonParam.getStr("rfid"));
        deviceBusiness.setBusinessFireId(jsonParam.getStr("businessFireId"));
        deviceBusiness.setUnit(jsonParam.getStr("unit"));
        if (jsonParam.containsKey("isChildren")){
            deviceBusiness.setIsChildren(jsonParam.getInt("isChildren"));
        }
        if ("8".equals(jsonParam.getStr("deviceClassify"))){
            deviceBusiness.setLedWidth(jsonParam.getStr("ledWidth"));
            deviceBusiness.setLedHeight(jsonParam.getStr("ledHeight"));
            deviceBusiness.setLedFontSize(jsonParam.getStr("ledFontSize"));
            deviceBusiness.setLedVolume(jsonParam.getStr("ledVolume"));
        }
        if ("6".equals(jsonParam.getStr("deviceClassify")) || "15".equals(jsonParam.getStr("deviceClassify"))|| "13".equals(jsonParam.getStr("deviceClassify"))){
            deviceBusiness.setPlayType(jsonParam.getStr("playType"));
            //设置播放时间
            jsonParam.put("playTime",20);
            setVideoPlayTime(jsonParam);
        }
        //远程抄表如果有分组则传分组ID
        if ("18".equals(jsonParam.getStr("deviceClassify"))){
            if (StrUtil.isNotBlank(jsonParam.getStr("ultrasonicGroupId"))){
                deviceBusiness.setUltrasonicGroupId(jsonParam.getStr("ultrasonicGroupId"));
            }
        }
        if (StrUtil.isNotBlank(jsonParam.getStr("createtime")))
            deviceBusiness.setCreatetime(jsonParam.getDate("createtime"));

        //添加图片
        if (jsonParam.containsKey("img") && StrUtil.isNotBlank(jsonParam.getStr("img"))) {
            String[] imgs = jsonParam.getStr("img").split(",");
            for (String img : imgs) {
                DeviceImg deviceImg = new DeviceImg();
                deviceImg.setDeviceId(jsonParam.getStr("id"));
                deviceImg.setId(UUID.randomUUID().toString());
                deviceImg.setName("设备图片地址");
                deviceImg.setPath(img);
                deviceImgMapper.insert(deviceImg);
            }
        }
        //添加视频流地址
        if (jsonParam.containsKey("videoplayAddrs") && StrUtil.isNotBlank(jsonParam.getStr("videoplayAddrs"))) {
            String[] videoplayAddrArr = jsonParam.getStr("videoplayAddrs").split(",");
            for (String addr : videoplayAddrArr) {
                DeviceBusinessVideoplayAddr deviceBusinessVideoplayAddr = new DeviceBusinessVideoplayAddr();
                deviceBusinessVideoplayAddr.setDeviceId(jsonParam.getStr("id"));
                deviceBusinessVideoplayAddr.setId(UUID.randomUUID().toString());
                deviceBusinessVideoplayAddr.setPath(addr);
                //rtspwfvideo1@消防支队对消控宝的标识
                if (!addr.contains("rtspwfvideo1@")){
                    deviceBusinessVideoplayAddrMapper.insert(deviceBusinessVideoplayAddr);
                }
            }
            deviceBusiness.setVideoplayAddr(videoplayAddrArr[0]);
        }
        deviceBusinessMapper.insert(deviceBusiness);
        return msg;
    }

    /**
     * 数据同步
     *
     * @param jsonParam
     * @throws Exception
     */
    public RespEntity devicesyn(JSONObject jsonParam) throws Exception {
        List<DeviceBusiness> deviceBusinessList = deviceBusinessMapper.selectList(new QueryWrapper<DeviceBusiness>().eq("number", jsonParam.getStr("number")));
        if (deviceBusinessList.isEmpty()) return RespEntity.fail("设备编号错误");
        DeviceBusiness deviceBusiness = deviceBusinessList.get(0);
        //rest请求单位详情接口，获取单位信息
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("id", deviceBusiness.getBusinessId());
        com.alibaba.fastjson.JSONObject businessDetail = makeData(jsonParamN, "businessJava", "config", "getBusinessDetailNoToken", "business");
        if (StrUtil.isNotBlank(businessDetail.getString("methodErrorFlag")))
            return RespEntity.fail(businessDetail.getString("msg"));
        //对接数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("DataType", jsonParam.getStr("DataType"));
        String xftoken = "";
        if (businessDetail.getString("orgId").equals("e349f82a-c7a7-4e67-a1ff-ae0aca8940f3")){
            //圣斌仁晟
            jsonObject.put("DevID", "AHH" + deviceBusiness.getNumber());
            xftoken =FirefightingiotKit.getStr("sbrsfirefightingToken","jointFire");
        }else {
            //智慧云
            jsonObject.put("DevID", "ABB" + deviceBusiness.getNumber());
            xftoken =FirefightingiotKit.getStr("zhyfirefightingToken","jointFire");
        }
        jsonObject.put("DevName", deviceBusiness.getPosition());
        jsonObject.put("AlarmTel", deviceBusiness.getInstallpersonPhone());
        //设备类型
        //电气火灾
        if (jsonParam.getStr("deviceClassify").equals("1")) {
            jsonObject.put("DevType", "01");
        } else if (jsonParam.getStr("deviceClassify").equals("2")) {//消防用水
            if (StrUtil.isBlank(deviceBusiness.getStr("waterattr"))) {
                jsonObject.put("DevType", "02");
            } else if (deviceBusiness.getWaterattr().equals("1")) {
                jsonObject.put("DevType", "02");
            } else if (deviceBusiness.getWaterattr().equals("2")) {
                jsonObject.put("DevType", "03");
            }
        } else if (jsonParam.getStr("deviceClassify").equals("3") && jsonParam.getStr("deviceType").equals("18")) {//烟感
            jsonObject.put("DevType", "06");
        } else if (jsonParam.getStr("deviceClassify").equals("6")) {//可视化
            jsonObject.put("DevType", "05");
            jsonObject.put("VideoUrl", deviceBusiness.getImg());
        } else if (jsonParam.getStr("deviceClassify").equals("5") && jsonParam.getStr("deviceType").equals("17")) {//用户传输装置
            jsonObject.put("DevType", "04");
        }else {
            return RespEntity.success();
        }
        //单位消防id
        String ComID = businessDetail.getString("fireId");
        jsonObject.put("ComID", ComID);
        jsonObject.put("ComName", jsonParam.getStr("businessName"));
        jsonObject.put("DevPos", jsonParam.getStr("position"));
        //电气火灾
        if (jsonParam.getStr("deviceClassify").equals("1")) {
            String electricityMinValue = FirefightingiotKit.getStr("electricityMinValue", "fire");
            String electricityMaxValue = FirefightingiotKit.getStr("electricityMaxValue", "fire");
            jsonObject.put("MinValue", electricityMinValue);
            jsonObject.put("MaxValue", electricityMaxValue);
        } else if (jsonParam.getStr("deviceClassify").equals("2")) {//消防用水
            if (StrUtil.isBlank(deviceBusiness.getStr("waterattr"))) {
                String electricityMinValue = FirefightingiotKit.getStr("waterPressureMinValue", "fire");
                String electricityMaxValue = FirefightingiotKit.getStr("waterPressureMaxValue", "fire");
                jsonObject.put("MinValue", electricityMinValue);
                jsonObject.put("MaxValue", electricityMaxValue);
            } else if (deviceBusiness.getWaterattr().equals("1")) {//水压
                String electricityMinValue = FirefightingiotKit.getStr("waterPressureMinValue", "fire");
                String electricityMaxValue = FirefightingiotKit.getStr("waterPressureMaxValue", "fire");
                jsonObject.put("MinValue", electricityMinValue);
                jsonObject.put("MaxValue", electricityMaxValue);
                jsonObject.put("MX", jsonParam.getStr("lon"));
                jsonObject.put("MY", jsonParam.getStr("lat"));
            } else if (deviceBusiness.getWaterattr().equals("2")) {//水位
                String electricityMinValue = FirefightingiotKit.getStr("waterLevelMinValue", "fire");
                String electricityMaxValue = FirefightingiotKit.getStr("waterLevelMaxValue", "fire");
                jsonObject.put("MinValue", electricityMinValue);
                jsonObject.put("MaxValue", electricityMaxValue);
                String str = jsonParam.getStr("spec").replaceAll("\\*", ";");
                String spec[] = str.split(";");
                jsonObject.put("Length", spec[0]);
                jsonObject.put("Width", spec[1]);
                jsonObject.put("Height", spec[2]);
            }
        }
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(jsonObject);
        logger.info("jsonArray++++++" + jsonArray);
        String fireFlag = ConfigKit.getStr("fireFlag", "config");
        if(fireFlag.equals("1")){
            return fireFightingiotArray(jsonArray, "fireBrigade", "deviceSyn", "jointFire",xftoken);
        }else{
            return RespEntity.success();
        }
    }

    /**
     * 设备操作分类功能：添加
     *
     * @param
     * @return
     */
    public RespEntity typeAdd(JSONObject jsonParam) throws Exception {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //rest请求token验证接口，并获取返回值：
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        if(userType.equals("1")){
            jsonParam.put("orgId",homeId);
        }else if(userType.equals("2")){
            jsonParam.put("businessId",homeId);
        }
        jsonParam.put("number",jsonParam.getStr("number").replace("\\r",""));
        //校验设备是否存在
        int deviceNum = deviceBusinessMapper.selectCount(new QueryWrapper<DeviceBusiness>().eq("number",jsonParam.getStr("number")));
        if (deviceNum > 0){
            return RespEntity.fail("设备已存在!");
        }
        //校验远程抄表设备是否重复
        if (jsonParam.getStr("deviceClassify").equals("18")){
            int ultrasonicDeviceNum = ultrasonicDeviceMapper.selectCount(new QueryWrapper<UltrasonicDevice>().eq("number",jsonParam.getStr("number")));
            if (ultrasonicDeviceNum > 0){
                return RespEntity.fail("设备已存在!");
            }
        }
        //判断是否输入正确规格
        if (jsonParam.getStr("deviceClassify").equals("2")) {
            if (jsonParam.getStr("deviceType").equals("2") || jsonParam.getStr("deviceType").equals("1")  ) {
                String spec = jsonParam.containsKey("spec")&&jsonParam.get("spec")!=null?jsonParam.getStr("spec"):"";
                if (!space(spec)){
                    return RespEntity.fail("请输入设备规格(设备长*宽*高)");
                }
            }
        }
        //rest请求单位详情接口，获取单位信息
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("id", jsonParam.getStr("businessId"));
        com.alibaba.fastjson.JSONObject businessDetail = makeData(jsonParamN, "businessJava", "config", "getBusinessDetailNoToken", "business");
        if (StrUtil.isNotBlank(businessDetail.getString("methodErrorFlag")))
            return RespEntity.fail(businessDetail.getString("msg"));
        jsonParam.put("businessName",businessDetail.getString("name"));
        jsonParam.put("orgId",businessDetail.getString("orgId"));
        jsonParam.put("businessFireId",businessDetail.getString("fireId"));
        jsonParam.put("DataType", "INSERT");
        jsonParamN.put("homeId",businessDetail.getString("orgId"));
        jsonParam.put("orgIds",businessDetail.getString("orgIds"));
        save(jsonParam);
        if ("6".equals(jsonParam.getStr("deviceClassify")) || "10".equals(jsonParam.getStr("deviceClassify")) || "11".equals(jsonParam.getStr("deviceClassify")) || "12".equals(jsonParam.getStr("deviceClassify")) || "13".equals(jsonParam.getStr("deviceClassify"))|| "15".equals(jsonParam.getStr("deviceClassify"))){
            QueryWrapper<DeviceBusiness> qw = new QueryWrapper<>();
            qw.eq("business_id",jsonParam.getStr("businessId"));
            qw.and(wrapper -> wrapper.eq("device_classify", "6").or().eq("device_classify", "10").or().eq("device_classify", "11").or().eq("device_classify", "12").or().eq("device_classify", "13").or().eq("device_classify", "15"));
            int count =  deviceBusinessMapper.selectCount(qw);
            if (count == 1 || count == 0){
                jsonParamN.put("cameraType","1");
                jsonParamN.put("businessId",jsonParam.getStr("businessId"));
                makeDataForJSONForToken(jsonParamN, "businessJava", "config", "updateCameraType", "business");
            }
        }
        return RespEntity.success(jsonParam);
    }

    /**
     * 设备操作分类功能：修改
     *
     * @param
     * @return
     */
    public RespEntity typeUpdate(JSONObject jsonParam) throws Exception {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //rest请求token验证接口，并获取返回值：
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        if (StrUtil.isBlank(jsonParam.getStr("id"))) {
            return RespEntity.fail("id不能为空");
        }
        DeviceBusiness deviceBusiness = deviceBusinessMapper.selectById(jsonParam.getStr("id"));
        if (deviceBusiness == null) {
            return RespEntity.fail("id不存在");
        }
        jsonParam.put("number",jsonParam.getStr("number").replace("\\r",""));
        //校验设备是否重复
        if (!deviceBusiness.getNumber().equals(jsonParam.getStr("number"))){
            int deviceNum = deviceBusinessMapper.selectCount(new QueryWrapper<DeviceBusiness>().eq("number",jsonParam.getStr("number")));
            if (deviceNum>0){
                return RespEntity.fail("设备已存在!");
            }
            //校验远程抄表设备是否重复
            if (jsonParam.getStr("deviceClassify").equals("18")){
                int ultrasonicDeviceNum = ultrasonicDeviceMapper.selectCount(new QueryWrapper<UltrasonicDevice>().eq("number",jsonParam.getStr("number")));
                if (ultrasonicDeviceNum > 0){
                    return RespEntity.fail("设备已存在!");
                }
            }
            if (deviceBusiness.getDeviceClassify().equals("19")){
                int count = deviceSwitchMapper.selectCount(new QueryWrapper<DeviceSwitch>().eq("trans_device_code",deviceBusiness.getNumber()));
                if (count > 0){
                    return RespEntity.fail("网关下存在开关设备，请删除再进行修改！");
                }
            }
            //为接入网关的时候
            if (jsonParam.getStr("deviceType").equals("1001")){
                UpdateWrapper<DeviceBusiness> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("trans_device_code",deviceBusiness.getNumber());
                DeviceBusiness updateDeviceBusiness = new DeviceBusiness();
                updateDeviceBusiness.setTransDeviceCode(jsonParam.getStr("number"));
                deviceBusinessMapper.update(updateDeviceBusiness,updateWrapper);
                DeviceBusiness updateDeviceBusiness1 = new DeviceBusiness();
                UpdateWrapper<DeviceBusiness> updateWrapper1 = new UpdateWrapper<>();
                updateWrapper1.setSql("number = REPLACE(number, '"+deviceBusiness.getNumber()+"', '"+jsonParam.getStr("number")+"')");
                updateWrapper1.eq("trans_device_code",jsonParam.getStr("number"));
                deviceBusinessMapper.update(updateDeviceBusiness1,updateWrapper1);
            }

        }
        //判断是否输入正确规格
        if (jsonParam.getStr("deviceClassify").equals("2")) {
            if (jsonParam.getStr("deviceType").equals("2") || jsonParam.getStr("deviceType").equals("1")  ) {
                String spec = jsonParam.containsKey("spec")&&jsonParam.get("spec")!=null?jsonParam.getStr("spec"):"";
                if (!space(spec)){
                    return RespEntity.fail("请输入设备规格(设备长*宽*高)");
                }
            }
        }
        //开关量监测
        if (jsonParam.getStr("deviceClassify").equals("19")){
            if (!deviceBusiness.getTransDeviceCode().equals(jsonParam.getStr("transDeviceCode"))){
                JSONObject json = new JSONObject();
                json.put("transDeviceCode",jsonParam.getStr("transDeviceCode"));
                json.put("oldTransDeviceCode",deviceBusiness.getTransDeviceCode());
                deviceSwitchService.updateTransDeviceCode(json);
            }
        }
        jsonParam.put("businessId",deviceBusiness.getBusinessId());
        jsonParam.put("businessName",deviceBusiness.getBusinessName());
        jsonParam.put("orgId",deviceBusiness.getOrgId());
        jsonParam.put("createtime",deviceBusiness.getCreatetime());
        jsonParam.put("currentstate",deviceBusiness.getCurrentstate());
        jsonParam.put("normalUpdateTime",deviceBusiness.getNormalUpdateTime());
        jsonParam.put("businessFireId", deviceBusiness.getBusinessFireId());
        jsonParam.put("orgIds",deviceBusiness.getAllId());
        jsonParam.put("DataType", "UPDATE");
        if ("6".equals(jsonParam.getStr("deviceClassify")) || "10".equals(jsonParam.getStr("deviceClassify")) || "11".equals(jsonParam.getStr("deviceClassify")) || "12".equals(jsonParam.getStr("deviceClassify")) || "13".equals(jsonParam.getStr("deviceClassify")) || "15".equals(jsonParam.getStr("deviceClassify"))){
            QueryWrapper<DeviceBusiness> qw = new QueryWrapper<>();
            qw.eq("business_id",jsonParam.getStr("businessId"));
            qw.and(wrapper -> wrapper.eq("device_classify", "6").or().eq("device_classify", "10").or().eq("device_classify", "11").or().eq("device_classify", "12").or().eq("device_classify", "13").or().eq("device_classify", "15"));
            int count =  deviceBusinessMapper.selectCount(qw);
            if (count > 0){
                jsonParam.put("cameraType","1");
                makeDataForJSONForToken(jsonParam, "businessJava", "config", "updateCameraType", "business");
            }else if (count == 0){
                jsonParam.put("cameraType","2");
                makeDataForJSONForToken(jsonParam, "businessJava", "config", "updateCameraType", "business");
            }
        }
        deviceBusinessMapper.deleteById(jsonParam.getStr("id"));
        deviceImgMapper.delete(new QueryWrapper<DeviceImg>().eq("device_id", jsonParam.getStr("id")));
        deviceBusinessVideoplayAddrMapper.delete(new QueryWrapper<DeviceBusinessVideoplayAddr>().eq("device_id", jsonParam.getStr("id")));
        save(jsonParam);
        return RespEntity.success();
    }
    //判断规格时调用
    public  boolean space(String str){
        String reg="^[0-9]*[1-9][0-9]*[*][0-9]*[1-9][0-9]*[*][0-9]*[1-9][0-9]*$";  //判断字符串中是否含有ll
        return str.matches(reg);
    }
    /**
     * 设备操作分类功能：删除
     *
     * @param
     * @return
     */
    public RespEntity typeDelete(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //rest请求token验证接口，并获取返回值：
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        if (StrUtil.isBlank(jsonParam.getStr("id"))) {
            return RespEntity.fail("id不能为空");
        }
        DeviceBusiness deviceBusiness = deviceBusinessMapper.selectById(jsonParam.getStr("id"));
        if (deviceBusiness == null) {
            return RespEntity.fail("id不存在");
        }
        int deviceChildren  = deviceBusinessMapper.selectCount(new QueryWrapper<DeviceBusiness>().eq("trans_device_code",deviceBusiness.getNumber()));
        int deviceSwitch  = deviceSwitchMapper.selectCount(new QueryWrapper<DeviceSwitch>().eq("trans_device_code",deviceBusiness.getNumber()));
        if (deviceChildren > 0 || deviceSwitch > 0){
            return RespEntity.fail("网关下存在设备无法删除!");
        }
        JSONObject json = new JSONObject();
        json.put("homeId",deviceBusiness.getId());
        makeDataForToken(json, "communicationJava", "config", "releaseNumberPieces", "communication");
        //删除设备
        deviceBusinessMapper.deleteById(jsonParam.getStr("id"));
        //删除设备图片
        deviceImgMapper.delete(new QueryWrapper<DeviceImg>().eq("device_id", jsonParam.getStr("id")));
        //删除视频流地址
        deviceBusinessVideoplayAddrMapper.delete(new QueryWrapper<DeviceBusinessVideoplayAddr>().eq("device_id", jsonParam.getStr("id")));
        //删除设备播放时间
        deviceVideoPlayTimeMapper.delete(new QueryWrapper<DeviceVideoPlayTime>().eq("number", deviceBusiness.getNumber()));
        //删除开关
        //deviceSwitchMapper.delete(new QueryWrapper<DeviceSwitch>().eq("trans_device_code",deviceBusiness.getTransDeviceCode()));
        if ("6".equals(jsonParam.getStr("deviceClassify")) || "10".equals(jsonParam.getStr("deviceClassify")) || "11".equals(jsonParam.getStr("deviceClassify")) || "12".equals(jsonParam.getStr("deviceClassify")) || "13".equals(jsonParam.getStr("deviceClassify")) || "15".equals(jsonParam.getStr("deviceClassify"))){
            QueryWrapper<DeviceBusiness> qw = new QueryWrapper<>();
            qw.eq("business_id",deviceBusiness.getBusinessId());
            qw.and(wrapper -> wrapper.eq("device_classify", "6").or().eq("device_classify", "10").or().eq("device_classify", "11").or().eq("device_classify", "12").or().eq("device_classify", "13").or().eq("device_classify", "15"));
            int count =  deviceBusinessMapper.selectCount(qw);
            jsonParam.put("businessId",deviceBusiness.getBusinessId());
            if (count > 0){
                jsonParam.put("cameraType","1");
                makeDataForJSONForToken(jsonParam, "businessJava", "config", "updateCameraType", "business");
            }else if (count == 0){
                jsonParam.put("cameraType","2");
                makeDataForJSONForToken(jsonParam, "businessJava", "config", "updateCameraType", "business");
            }
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 查询单位下的所有摄像头
     * @Date Created in 11:31 2021/3/25
     * @Param [jsonParam]
     */

    public RespEntity deviceCameraList(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String businessId = "";
        if (StrUtil.isNotBlank(jsonParam.getStr("businessId")) || jsonParam.getStr("businessId") != null){
            businessId = jsonParam.getStr("businessId");
        }else {
            businessId = homeId;
        }

        QueryWrapper<DeviceBusiness> userWrapper = new QueryWrapper<DeviceBusiness>();
        userWrapper.eq("business_id", businessId);
        userWrapper.and(wrapper -> wrapper.eq("device_classify", "6").or().eq("device_classify", "15").or().eq("device_classify", "13"));

        List<DeviceBusiness> deviceCameraList = deviceBusinessMapper.selectList(userWrapper);

        return RespEntity.success(deviceCameraList);
    }

    /**
     * @Author YangYu
     * @Description 查询单位下的led,ip音柱，鹰眼e通设备列表
     * @Date Created in 11:31 2021/3/25
     * @Param [jsonParam]
     */

    public RespEntity deviceList(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String businessId = "";
        if (StrUtil.isNotBlank(jsonParam.getStr("businessId")) || jsonParam.getStr("businessId") != null){
            businessId = jsonParam.getStr("businessId");
        }else {
            businessId = homeId;
        }
        String[] businessIdList = businessId.split(",");
        //要查询的单位id
        List<JSONObject> list = new ArrayList<>();
        for (String id : businessIdList){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("businessId",id);
            list.add(jsonObject);
        }
        //鹰眼e通
        if (jsonParam.getStr("deviceClassify").equals("6")){
            jsonParam.put("productId","6002");
        }
        List<DeviceBusiness> deviceBusinessList = deviceBusinessMapper.getDeviceListZB(jsonParam,list);
        return RespEntity.success(deviceBusinessList);
    }

    /**
     * @Author YangYu
     * @Description 查询单位下的led,ip音柱，鹰眼e通设备列表
     * @Date Created in 11:31 2021/3/25
     * @Param [jsonParam]
     */

    public RespEntity deviceListNew(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(new JSONObject(), "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String businessId = "";
        if (StrUtil.isNotBlank(jsonParam.getStr("businessId")) || jsonParam.getStr("businessId") != null){
            businessId = jsonParam.getStr("businessId");
        }else {
            businessId = homeId;
        }
        String[] businessIdList = businessId.split(",");
        //要查询的单位id
        List<JSONObject> list = new ArrayList<>();
        for (String id : businessIdList){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("businessId",id);
            list.add(jsonObject);
        }
        //鹰眼e通
        if (jsonParam.getStr("deviceClassify").equals("6")){
            jsonParam.put("productId","6002");
        }
        List<DeviceBusiness> deviceBusinessList = deviceBusinessMapper.getDeviceListZB(jsonParam,list);
        return RespEntity.success(deviceBusinessList);
    }

    /**
     * 设备类型列表
     *
     * @param
     * @return
     */
    public RespEntity deviceTypeList(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject jSONObject = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(jSONObject.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(jSONObject.getString("methodErrorFlag")))
            return RespEntity.fail(jSONObject.getString("msg"));
        String type = jsonParam.getStr("type");
        if (type.equals("11") || type.equals("12") || type.equals("13") || type.equals("14") || type.equals("15") || type.equals("16") || type.equals("17")){
            type = "6";
        }
        List<DeviceType> list = deviceTypeMapper.selectList(new QueryWrapper<DeviceType>().eq("type", type).eq("product_id",jsonParam.getStr("productId")).orderByAsc("sort"));
        DeviceType deviceType = new DeviceType();
        deviceType.setId("1001");
        deviceType.setName("接入网关");
        deviceType.setType(jsonParam.getStr("type"));
        deviceType.setProductId(null);
        list.add(deviceType);
        return RespEntity.success(list);
    }

    /**
     * 设备列表
     *
     * @param
     * @return
     */
    public RespEntity deviceListPage(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        Page<DeviceBusiness> page = new Page<>(jsonParam.getInt("page"), jsonParam.getInt("limit"));
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        if (userType.equals("1")) {//为机构用户
            //rest请求系统设置模块的机构和子机构列表接口
            if (StrUtil.isNotBlank(jsonParam.getStr("businessId"))) {//机构用户访问单位用户的数据
                jsonParam.put("businessId", jsonParam.getStr("businessId"));
            } else if (!jsonParam.containsKey("orgId") || StrUtil.isBlank(jsonParam.getStr("orgId"))){
                jsonParam.put("orgId", homeId);
            }
        } else if (userType.equals("2")) {//为单位用户
            jsonParam.put("businessId", homeId);
        }
        if(jsonParam.containsKey("alarmType") && StrUtil.isNotBlank(jsonParam.getStr("alarmType"))){
            List<String> numberList = deviceBusinessMapper.getNumbersByAlarmType(jsonParam);
            if(!numberList.isEmpty()){
                jsonParam.put("numberFlag","1");
                jsonParam.put("numberList",numberList);
            }
        }
        if(jsonParam.containsKey("deviceType") && StrUtil.isNotBlank(jsonParam.getStr("deviceType"))){
            List<String> numberList = deviceBusinessMapper.getNumbersByDeviceType(jsonParam);
            if(!numberList.isEmpty()){
                jsonParam.put("numberFlag","1");
                jsonParam.put("numberList",numberList);
            }
        }
        IPage<DeviceBusiness> pageList = deviceBusinessMapper.deviceListPage(page, jsonParam);
        Map<String, Object> data = new HashMap<>();
        data.put("totalSize", pageList.getTotal());//总条数
        data.put("pageSize", pageList.getSize());//每页展示多少条
        data.put("currentPage", pageList.getCurrent());//当前页
        data.put("Items", pageList.getRecords());//数据
        data.put("pages", pageList.getPages());//总页数
        data.put("currentSize", pageList.getRecords().size());//当前页多少条
        return RespEntity.success(data);
    }

    /**
     * 设备详情
     *
     * @param
     * @return
     */
    public RespEntity detail(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        if (StrUtil.isBlank(jsonParam.getStr("id")) && StrUtil.isBlank(jsonParam.getStr("rfid")) && StrUtil.isBlank(jsonParam.getStr("number")))
            return RespEntity.fail("传入参数不正确");
        DeviceBusiness deviceBusiness = deviceBusinessMapper.getByParam(jsonParam);
        if (deviceBusiness == null) return RespEntity.fail("传入参数不正确");
        List<DeviceImg> imgOldList = deviceImgMapper.selectList(new QueryWrapper<DeviceImg>().eq("device_id", jsonParam.getStr("id")));
        List<DeviceBusinessVideoplayAddr> videoplayAddrOldList = deviceBusinessVideoplayAddrMapper.selectList(new QueryWrapper<DeviceBusinessVideoplayAddr>().eq("device_id", deviceBusiness.getId()));
        List<String> imgList = new ArrayList<>();
        for (DeviceImg img : imgOldList) {
            imgList.add(img.getPath());
        }
        List<String> videoplayAddrList = new ArrayList<>();
        for (DeviceBusinessVideoplayAddr addr : videoplayAddrOldList) {
            videoplayAddrList.add(addr.getPath());
        }
        deviceBusiness.put("imgList", imgList);
        deviceBusiness.put("videoplayAddrList", videoplayAddrList);
        return RespEntity.success(deviceBusiness);
    }
    /**
     * 设备详情(不带token)
     * @param
     * @return
     */
    public RespEntity deviceDetail(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        if (StrUtil.isBlank(jsonParam.getStr("id")) && StrUtil.isBlank(jsonParam.getStr("rfid")) && StrUtil.isBlank(jsonParam.getStr("number")))
            return RespEntity.fail("传入参数不正确");
        DeviceBusiness deviceBusiness = deviceBusinessMapper.getByParam(jsonParam);
        if (deviceBusiness == null) return RespEntity.fail("传入参数不正确");
        List<DeviceImg> imgOldList = deviceImgMapper.selectList(new QueryWrapper<DeviceImg>().eq("device_id", jsonParam.getStr("id")));
        List<DeviceBusinessVideoplayAddr> videoplayAddrOldList = deviceBusinessVideoplayAddrMapper.selectList(new QueryWrapper<DeviceBusinessVideoplayAddr>().eq("device_id", deviceBusiness.getId()));
        List<String> imgList = new ArrayList<>();
        for (DeviceImg img : imgOldList) {
            imgList.add(img.getPath());
        }
        List<String> videoplayAddrList = new ArrayList<>();
        for (DeviceBusinessVideoplayAddr addr : videoplayAddrOldList) {
            videoplayAddrList.add(addr.getPath());
        }
        deviceBusiness.put("imgList", imgList);
        deviceBusiness.put("videoplayAddrList", videoplayAddrList);
        return RespEntity.success(deviceBusiness);
    }
    //组装小项名称和实时数据值的映射
    public JSONObject getElectricFireItemMap(JSONArray jSONArray, List<String> nameList) {
        JSONObject jSONObject = new JSONObject();//组装最终数据
        Map<String, String> map = getFieldItemMap();//获取正常二级数据项和正常数据日志字段的映射
        for (int i = 0; i < jSONArray.size(); i++) {
            JSONObject item = (JSONObject) jSONArray.get(i);
            if (!nameList.contains(item.getStr("name"))) continue;//如果数据库找不大，直接舍去
            if (item.getStr("value")==null||StrUtil.isBlank(item.getStr("value"))) continue;
            //保留两位小数
            DecimalFormat df = new DecimalFormat("#.##");
            try {
                jSONObject.put(map.get(item.getStr("name")),df.format(item.getDouble("value")));//组装最终存表的字段名和值的映射
            }catch (Exception e){
                continue;
            }
        }
        return jSONObject;
    }

    //获取正常二级数据项和正常数据日志字段的映射
    public Map<String, String> getFieldItemMap() {
        Map<String, String> map = new HashMap<>();//组装数据
        //获取获取正常二级数据项和正常数据日志字段的映射关系列表
        List<ItemLogFieldMapping> list = itemLogFieldMappingMapper.selectList(new QueryWrapper<>());
        for (ItemLogFieldMapping mapping : list) {
            map.put(mapping.getItemName(), mapping.getLogValueName());
        }
        return map;
    }
    /**
     * 设备正常数据保存
     *
     * @param
     * @return
     */
    public RespEntity normalDataLogAdd(JSONObject jsonParam) {
        logger.info("-------------------------------------normalDataLogAdd------------------------" + jsonParam.toString());
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        List<DeviceBusiness> deviceBusinessList = deviceBusinessMapper.selectList(new QueryWrapper<DeviceBusiness>().eq("number", jsonParam.getStr("number")));
        if (deviceBusinessList.isEmpty()) return RespEntity.fail("设备编号不存在");
        DeviceBusiness deviceBusiness = deviceBusinessList.get(0);
        //更新最新时间的和设备的状态为在线
        DeviceBusiness deviceBusinessN = new DeviceBusiness();
        deviceBusinessN.setId(deviceBusiness.getId());
        deviceBusinessN.setNormalUpdateTime(DateUtil.now());
        if (!deviceBusiness.getCurrentstate().equals("2")) {
            deviceBusinessN.setCurrentstate("1");
        }
        deviceBusinessMapper.updateById(deviceBusinessN);
        jsonParam.put("deviceClassify", deviceBusiness.getDeviceClassify());
        String senddate = "";
        String sendtime = "";
        String time = jsonParam.getStr("time");
        if (StrUtil.isBlank(time)) return RespEntity.fail("time为空");
        String times[] = time.split(" ");
        senddate = times[0];
        sendtime = times[1];
        JSONArray jSONArray = jsonParam.getJSONArray("paraminfo");
        Dict fireMap = new Dict();
        //获取所有的二级正常数据项
        List<DeviceNormalItems> deviceNormalItemsList = deviceNormalItemsMapper.selectList(new QueryWrapper<DeviceNormalItems>().eq("level", 2));
        List<String> nameList = new ArrayList<>();
        for (DeviceNormalItems item : deviceNormalItemsList) {
            nameList.add(item.getName());
        }
        //获取最终插入表字段名和值的映射关系
        JSONObject fieldValueMap = getElectricFireItemMap(jSONArray, nameList);
        //存放正常数据项之外的数据
        fieldValueMap.put("id", UUID.randomUUID().toString());
        fieldValueMap.put("device_id", deviceBusiness.getId());
        fieldValueMap.put("number", deviceBusiness.getNumber());
        fieldValueMap.put("senddate", DateUtil.parseDate(senddate));
        fieldValueMap.put("sendtime", sendtime);
        fieldValueMap.put("business_id", deviceBusiness.getBusinessId());
        fieldValueMap.put("business_name", deviceBusiness.getBusinessName());
        //保存最终数据到正常数据日志表
        if (jsonParam.getStr("deviceClassify").equals("1")) {//电气火灾
            fieldValueMap.put("table", "device_normal_log_electric_fire_" + DayUtil.getToday());
            deviceNormalLogMapper.inserDeviceNormalLogElectricFire(fieldValueMap);
            //在总表存储一份
            fieldValueMap.put("table", "device_normal_log_all");
            deviceNormalLogMapper.inserDeviceNormalLogElectricFire(fieldValueMap);
            //涛思

        } else if (jsonParam.getStr("deviceClassify").equals("2")) {//消防用水
            fieldValueMap.put("table", "device_normal_log_fire_water_" + DayUtil.getToday());
            deviceNormalLogMapper.inserDeviceNormalLogFireWater(fieldValueMap);
            //在总表存储一份
            fieldValueMap.put("table", "device_normal_log_all");
            deviceNormalLogMapper.inserDeviceNormalLogFireWater(fieldValueMap);
        } else if (jsonParam.getStr("deviceClassify").equals("3")) {//烟感
            fieldValueMap.put("table", "device_normal_log_smoke_" + DayUtil.getToday());
            deviceNormalLogMapper.inserDeviceNormalLogSmoke(fieldValueMap);
            //在总表存储一份
            fieldValueMap.put("table", "device_normal_log_all");
            deviceNormalLogMapper.inserDeviceNormalLogSmoke(fieldValueMap);
        } else if (jsonParam.getStr("deviceClassify").equals("4")) {//可燃气体
            fieldValueMap.put("table", "device_normal_log_gas_" + DayUtil.getToday());
            deviceNormalLogMapper.inserDeviceNormalLogGas(fieldValueMap);
            //在总表存储一份
            fieldValueMap.put("table", "device_normal_log_all");
            deviceNormalLogMapper.inserDeviceNormalLogGas(fieldValueMap);
        }else if (jsonParam.getStr("deviceClassify").equals("7")) {//灭火器
            fieldValueMap.put("table", "device_normal_log_extinguisher_" + DayUtil.getToday());
            deviceNormalLogMapper.inserDeviceNormalLogExtinguisher(fieldValueMap);
            //在总表存储一份
            fieldValueMap.put("table", "device_normal_log_all");
            deviceNormalLogMapper.inserDeviceNormalLogExtinguisher(fieldValueMap);
        }
        return RespEntity.success();
    }

    /**
     * 设备正常数据查询
     *
     * @param
     * @return
     */
    public RespEntity normalDataLogList(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        List<Map<String, Object>> oneList = new ArrayList<>();
        DeviceBusiness u = deviceBusinessMapper.getDeviceBusinessById(jsonParam);//设备详情
        DeviceType deviceType = deviceTypeMapper.selectById(u.getDeviceType());
        u.set("deviceTypeName",deviceType.getName());
        u.put("updatetime", DateUtil.now());//更新时间，页面显示
        Map<String, Object> map = new HashMap<>();
        map.put("deviceDetail", u);
        if (jsonParam.getStr("deviceClassify").equals("1") && jsonParam.getStr("tabflag").equals("1")) {//电气火灾第一个tab
            //今日报警
            Integer todayVoltageCount = 0;//电压报警数目
            Integer todayCurrentCount = 0;//电流报警数目
            Integer todayTemperatureCount = 0;//温度报警数目
            Integer todayLeakageCurrentCount = 0;//漏电流报警数目
            List<Map<String, Object>> alarmMapList = deviceAlarmLogAllTodayMapper.selectEleGroupByAlarmType(jsonParam);
            for(Map<String, Object> alarmMap : alarmMapList){
                if(alarmMap.get("alarmTypeName").equals("电压报警")){
                    todayVoltageCount = Integer.parseInt(alarmMap.get("count").toString());
                }else if(alarmMap.get("alarmTypeName").equals("电流报警")){
                    todayCurrentCount = Integer.parseInt(alarmMap.get("count").toString());
                }else if(alarmMap.get("alarmTypeName").equals("温度报警")){
                    todayTemperatureCount = Integer.parseInt(alarmMap.get("count").toString());
                }else if(alarmMap.get("alarmTypeName").equals("漏电流报警")){
                    todayLeakageCurrentCount = Integer.parseInt(alarmMap.get("count").toString());
                }
            }
            Integer allCount = todayVoltageCount + todayCurrentCount + todayTemperatureCount + todayLeakageCurrentCount;//总数目
            Map<String, Object> todayAlarm = new HashMap<>();//存储今日报警的一些相关信息
            todayAlarm.put("todayVoltageCount",todayVoltageCount);
            todayAlarm.put("todayCurrentCount",todayCurrentCount);
            todayAlarm.put("todayTemperatureCount",todayTemperatureCount);
            todayAlarm.put("todayLeakageCurrentCount",todayLeakageCurrentCount);
            todayAlarm.put("allCount",allCount);
            //百分比
            todayAlarm.put("voltageProportion",allCount==0?0: NumberUtil.roundStr(((double)todayVoltageCount)*100/allCount,2));
            todayAlarm.put("currentProportion",allCount==0?0:NumberUtil.roundStr(((double)todayCurrentCount)*100/allCount,2));
            todayAlarm.put("temperatureProportion",allCount==0?0:NumberUtil.roundStr(((double)todayTemperatureCount)*100/allCount,2));
            todayAlarm.put("leakageCurrentProportion",allCount==0?0:NumberUtil.roundStr(((double)todayLeakageCurrentCount)*100/allCount,2));
            map.put("alarmData", todayAlarm);
        }else if (jsonParam.getStr("deviceClassify").equals("22") && jsonParam.getStr("tabflag").equals("1") && u.getDeviceType().equals("33")) {//充电桩电气火灾第一个tab
            //今日报警
            Integer todayVoltageCount = 0;//电压报警数目
            Integer todayCurrentCount = 0;//电流报警数目
            Integer todayTemperatureCount = 0;//温度报警数目
            Integer todayLeakageCurrentCount = 0;//漏电流报警数目
            List<Map<String, Object>> alarmMapList = deviceAlarmLogAllTodayMapper.selectChargingStationGroupByAlarmType(jsonParam);
            for(Map<String, Object> alarmMap : alarmMapList){
                if(alarmMap.get("alarmTypeName").equals("电压报警")){
                    todayVoltageCount = Integer.parseInt(alarmMap.get("count").toString());
                }else if(alarmMap.get("alarmTypeName").equals("电流报警")){
                    todayCurrentCount = Integer.parseInt(alarmMap.get("count").toString());
                }else if(alarmMap.get("alarmTypeName").equals("温度报警")){
                    todayTemperatureCount = Integer.parseInt(alarmMap.get("count").toString());
                }else if(alarmMap.get("alarmTypeName").equals("漏电流报警")){
                    todayLeakageCurrentCount = Integer.parseInt(alarmMap.get("count").toString());
                }
            }
            Integer allCount = todayVoltageCount + todayCurrentCount + todayTemperatureCount + todayLeakageCurrentCount;//总数目
            Map<String, Object> todayAlarm = new HashMap<>();//存储今日报警的一些相关信息
            todayAlarm.put("todayVoltageCount",todayVoltageCount);
            todayAlarm.put("todayCurrentCount",todayCurrentCount);
            todayAlarm.put("todayTemperatureCount",todayTemperatureCount);
            todayAlarm.put("todayLeakageCurrentCount",todayLeakageCurrentCount);
            todayAlarm.put("allCount",allCount);
            //百分比
            todayAlarm.put("voltageProportion",allCount==0?0: NumberUtil.roundStr(((double)todayVoltageCount)*100/allCount,2));
            todayAlarm.put("currentProportion",allCount==0?0:NumberUtil.roundStr(((double)todayCurrentCount)*100/allCount,2));
            todayAlarm.put("temperatureProportion",allCount==0?0:NumberUtil.roundStr(((double)todayTemperatureCount)*100/allCount,2));
            todayAlarm.put("leakageCurrentProportion",allCount==0?0:NumberUtil.roundStr(((double)todayLeakageCurrentCount)*100/allCount,2));
            map.put("alarmData", todayAlarm);
        }
        String time = jsonParam.getStr("time");
        String[] times = jsonParam.getStr("time").split("-");
        String queryTime = times[0] + (times[1].length() == 1 ? ("0" + times[1]) : times[1]) + (times[2].length() == 1 ? ("0" + times[2]) : times[2]);
        jsonParam.put("queryTime", queryTime);
        oneList = getList(jsonParam);
        map.put("oneList", oneList);
        return RespEntity.success(map);
    }

    //获取正常二级数据项和正常数据日志字段的映射
    public Map<String, String> getFieldItemUnderlineMap() {
        Map<String, String> map = new HashMap<>();//组装数据
        //获取获取正常二级数据项和正常数据日志字段的映射关系列表
        List<ItemLogFieldMapping> list = itemLogFieldMappingMapper.selectList(new QueryWrapper<>());
        for (ItemLogFieldMapping mapping : list) {
            map.put(mapping.getItemName(), mapping.getNoUnderLineName());
        }
        return map;
    }

    //根据小项名称获取数值集合：smallItemName：小项名称；valueList：这个设备的查询日期的数据
    public List<Map<String, Object>> getValueListBySmallItem(String smallItemName, List<Map<String, Object>> valueList, Map<String, String> fieldItemMap) {
        List<Map<String, Object>> valueAllList = new ArrayList<>();//定义组装数据
        for (Map<String, Object> str : valueList) {
            if (str.get(fieldItemMap.get(smallItemName)) != null && StrUtil.isNotBlank(str.get(fieldItemMap.get(smallItemName)).toString())) {
                Map<String, Object> valueMap = new HashMap<>();
                valueMap.put("value", str.get(fieldItemMap.get(smallItemName)));
                valueMap.put("sendtime", str.get("sendtime"));
                valueAllList.add(valueMap);
            }
        }
        return valueAllList;
    }

    //正常数据的查询
    public List<Map<String, Object>> getList(JSONObject jsonParam) {
        //查询设备某个日期的值
        List<Map<String, Object>> valueAllList = new ArrayList<>();
        if (jsonParam.getStr("deviceClassify").equals("1")) {//电气火灾
            String tableName = deviceNormalLogMapper.haveTable("device_normal_log_electric_fire_" + jsonParam.getStr("queryTime"));
            if (tableName == null || tableName.equals("")) {
                return valueAllList;
            }
            jsonParam.put("table", "device_normal_log_electric_fire_" + jsonParam.getStr("queryTime"));
            valueAllList = deviceNormalLogMapper.getValueListByNumberForElectricFire(jsonParam);
        } else if (jsonParam.getStr("deviceClassify").equals("2")) {//消防用水
            String tableName = deviceNormalLogMapper.haveTable("device_normal_log_fire_water_" + jsonParam.getStr("queryTime"));
            if (tableName == null || tableName.equals("")) {
                return valueAllList;
            }
            jsonParam.put("table", "device_normal_log_fire_water_" + jsonParam.getStr("queryTime"));
            valueAllList = deviceNormalLogMapper.getValueListByNumberForFireWater(jsonParam);
        } else if (jsonParam.getStr("deviceClassify").equals("3")) {//烟感
            String tableName = deviceNormalLogMapper.haveTable("device_normal_log_smoke_" + jsonParam.getStr("queryTime"));
            if (tableName == null || tableName.equals("")) {
                return valueAllList;
            }
            jsonParam.put("table", "device_normal_log_smoke_" + jsonParam.getStr("queryTime"));
            valueAllList = deviceNormalLogMapper.getValueListByNumberForSmoke(jsonParam);
        } else if (jsonParam.getStr("deviceClassify").equals("4")) {//可燃气体
            String tableName = deviceNormalLogMapper.haveTable("device_normal_log_gas_" + jsonParam.getStr("queryTime"));
            if (tableName == null || tableName.equals("")) {
                return valueAllList;
            }
            jsonParam.put("table", "device_normal_log_gas_" + jsonParam.getStr("queryTime"));
            valueAllList = deviceNormalLogMapper.getValueListByNumberForGas(jsonParam);
        }else if (jsonParam.getStr("deviceClassify").equals("7")) {//灭火器
            String tableName = deviceNormalLogMapper.haveTable("device_normal_log_extinguisher_" + jsonParam.getStr("queryTime"));
            if (tableName == null || tableName.equals("")) {
                return valueAllList;
            }
            jsonParam.put("table", "device_normal_log_extinguisher_" + jsonParam.getStr("queryTime"));
            valueAllList = deviceNormalLogMapper.getValueListByNumberForExtinguisher(jsonParam);
        }else if (jsonParam.getStr("deviceClassify").equals("10")) {//水泵
            String tableName = deviceNormalLogMapper.haveTable("device_normal_log_water_pump_" + jsonParam.getStr("queryTime"));
            if (tableName == null || tableName.equals("")) {
                return valueAllList;
            }
            jsonParam.put("table", "device_normal_log_water_pump_" + jsonParam.getStr("queryTime"));
            valueAllList = deviceNormalLogMapper.getValueListByNumberForWaterPump(jsonParam);
        }else if (jsonParam.getStr("deviceClassify").equals("21")) {//温湿度
            String tableName = deviceNormalLogMapper.haveTable("device_normal_log_temperature_humidity_" + jsonParam.getStr("queryTime"));
            if (tableName == null || tableName.equals("")) {
                return valueAllList;
            }
            jsonParam.put("table", "device_normal_log_temperature_humidity_" + jsonParam.getStr("queryTime"));
            valueAllList = deviceNormalLogMapper.getValueListByNumberForTemperatureHumidity(jsonParam);
        }else if (jsonParam.getStr("deviceClassify").equals("22")) {//充电桩
            String tableName = deviceNormalLogMapper.haveTable("device_normal_log_charging_station_" + jsonParam.getStr("queryTime"));
            if (tableName == null || tableName.equals("")) {
                return valueAllList;
            }
            jsonParam.put("table", "device_normal_log_charging_station_" + jsonParam.getStr("queryTime"));
            valueAllList = deviceNormalLogMapper.getValueListByNumberForChargingStation(jsonParam);
        }
        //查询涛思数据库
//        com.alibaba.fastjson.JSONArray valueResult = taos(jsonParam, "sequential", "select", "sequential","get");
//        valueAllList = new ArrayList<>();
//        for(Object oo : valueResult){
//            com.alibaba.fastjson.JSONObject jsonMap = (com.alibaba.fastjson.JSONObject)oo;
//            Map map = jsonMap.getInnerMap();
//            valueAllList.add(map);
//        }
        if (jsonParam.getStr("deviceClassify").equals("22")){
            jsonParam.put("deviceClassify","1");
        }
        //查询大项和小项的名称
        List<NormalBigItemsDo> onetempList = deviceNormalItemsMapper.getNormalBigItemsDoList(jsonParam);
        //获取正常二级数据项和正常数据日志字段的映射
        Map<String, String> fieldItemMap = getFieldItemUnderlineMap();
        //定义组装项列表
        List<Map<String, Object>> oneList = new ArrayList<>();
        //组装修改大项的显示名称key和名称key
        for (NormalBigItemsDo bigDo : onetempList) {
            Map<String, Object> bigMap = new HashMap<>();
            bigMap.put("name", bigDo.getBigName());
            bigMap.put("displayName", bigDo.getBigDisplayName());
            List<NormalSmallItemsDo> twoList = bigDo.getTwoList();
            for (NormalSmallItemsDo small : twoList) {
                //赋值值的列表
                List<Map<String, Object>> valueList = getValueListBySmallItem(small.getName(), valueAllList, fieldItemMap);
                small.put("valueList", valueList);
                if (!valueList.isEmpty()) {
                    small.put("value", valueList.get(valueList.size() - 1).get("value"));
                } else {
                    small.put("value", "0");
                }
            }
            bigMap.put("twoList", twoList);
            oneList.add(bigMap);
        }
        return oneList;
    }

    /**
     * 电气火灾其他参数列表
     *
     * @param
     * @return
     */
    public RespEntity eleNormalOtherList(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        List<DeviceNormalItems> oneList = deviceNormalItemsMapper.selectList(new QueryWrapper<DeviceNormalItems>().eq("device_classify", "1").eq("tabflag", 3).eq("level", 1).orderByAsc("id"));
        return RespEntity.success(oneList);
    }

    /**
     * 今日每个时刻的报警数目统计
     *
     * @param
     * @return
     */
    public RespEntity todayNormalDataLogNumByMin(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject jSONObject = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(jSONObject.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(jSONObject.getString("methodErrorFlag")))
            return RespEntity.fail(jSONObject.getString("msg"));
        //解析出token中的数据
        String home_id = jSONObject.getString("home_id");
        String user_type = jSONObject.getString("user_type");
        String user_id = jSONObject.getString("user_id");
        if (user_type.equals("1")){
            jsonParam.put("orgId", home_id);
        }else {
            jsonParam.put("businessId", home_id);
        }
        jsonParam.put("alarmtime", DateUtil.now());
        //获取今日每个时刻的数据
        List<String> list = deviceAlarmLogMapper.getTodayList(jsonParam);
        return RespEntity.success(getAllTimeList(list));
    }

    //字符串去重处理
    public String strRemoveRepeat(String str) {
        String newStr = "";
        List<String> strList = new ArrayList<>();
        if (StrUtil.isNotBlank(str)) {
            String[] arrs = newStr.split(",");
            for (String s : arrs) {
                if (StrUtil.isNotBlank(s.trim()) && !strList.contains(s.trim())) {
                    strList.add(s.trim());
                }
            }
            if (!strList.isEmpty()) {
                for (String s : strList) {
                    newStr = s + ",";
                }
                newStr = newStr.substring(0, newStr.length() - 1);
            }
        }
        return newStr;
    }

    //获取24小时的list
    public List<Map<String, Object>> getAllTimeList(List<String> list) {
        List<Map<String, Object>> allList = new ArrayList<>();
        allList.add(getNumFormList("00", list));
        allList.add(getNumFormList("01", list));
        allList.add(getNumFormList("02", list));
        allList.add(getNumFormList("03", list));
        allList.add(getNumFormList("04", list));
        allList.add(getNumFormList("05", list));
        allList.add(getNumFormList("06", list));
        allList.add(getNumFormList("07", list));
        allList.add(getNumFormList("08", list));
        allList.add(getNumFormList("09", list));
        allList.add(getNumFormList("10", list));
        allList.add(getNumFormList("11", list));
        allList.add(getNumFormList("12", list));
        allList.add(getNumFormList("13", list));
        allList.add(getNumFormList("14", list));
        allList.add(getNumFormList("15", list));
        allList.add(getNumFormList("16", list));
        allList.add(getNumFormList("17", list));
        allList.add(getNumFormList("18", list));
        allList.add(getNumFormList("19", list));
        allList.add(getNumFormList("20", list));
        allList.add(getNumFormList("21", list));
        allList.add(getNumFormList("22", list));
        allList.add(getNumFormList("23", list));
        return allList;
    }

    //获取list中包含某字符串的数量
    public Map<String, Object> getNumFormList(String str, List<String> list) {
        int num = 0;
        Map<String, Object> map = new HashMap();
        for (String s : list) {
            if (s.equals(str)) {
                num = num + 1;
            }
        }
        map.put("time", str);
        map.put("alarmSum", num);
        return map;
    }

    /**
     * 更改设备的离线状态
     *
     * @param
     * @return
     */
    public RespEntity offDeviceListUpdate(JSONArray jSONArray) {
        if (!jSONArray.isEmpty()) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("list", jSONArray);
            DeviceBusiness deviceBusiness = new DeviceBusiness();
            deviceBusiness.setCurrentstate("1");
            //先还原
            deviceBusinessMapper.update(deviceBusiness, new QueryWrapper<DeviceBusiness>().eq("currentstate", 3));
            //在刷新成现在的离线状态
            deviceBusinessMapper.updateCurrentstateByNumbers(jsonObject);
        }
        List<DeviceBusiness> list = deviceBusinessMapper.selectList(new QueryWrapper<DeviceBusiness>().eq("currentstate", 3).isNotNull("device_classify"));
        JSONArray fireList = new JSONArray();//电气火灾
        JSONArray waterList = new JSONArray();//建筑消防用水
        JSONArray smokeList = new JSONArray();//烟感
        JSONArray visList = new JSONArray();//可视化
        JSONArray gasList = new JSONArray();//可燃气体
        if (!list.isEmpty()) {
            for (DeviceBusiness de : list) {
                if (de.getDeviceClassify().equals("1")) {
                    fireList.add(de.getNumber());
                } else if (de.getDeviceClassify().equals("2")) {
                    waterList.add(de.getNumber());
                } else if (de.getDeviceClassify().equals("3")) {
                    smokeList.add(de.getNumber());
                } else if (de.getDeviceClassify().equals("4")) {
                    gasList.add(de.getNumber());
                } else if (de.getDeviceClassify().equals("5")) {
                    fireList.add(de.getNumber());
                } else if (de.getDeviceClassify().equals("6")) {
                    visList.add(de.getNumber());
                }
            }
        }
        return RespEntity.success();
    }

    //消防物联网
    public void fireFightingiot(JSONArray jSONArray, String configKey, String key, String gp) {
        String ip = ConfigKit.getStr(configKey, "config");
        String methodPath = FirefightingiotKit.getStr(key, gp);
        String domain = ip + methodPath;
        String xml = HttpRequest.post(domain).body(jSONArray.toJSONString(1)).execute().body();
    }

    /**
     * 单位评估调用服务
     * 查询是否接入设备
     *
     * @param jsonParam
     * @return
     */
    public Integer getDeviceCount(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        Integer integer = deviceBusinessMapper.getDeviceCount(jsonParam);

        return integer;
    }

    /**
     * 单位名称修改时调用服务
     * 修改设备表和报警日志表的单位名称服务
     * @param jsonObject
     * @return
     */
    @Async
    public RespEntity updateBusinessName(JSONObject jsonObject){
        //修改设备表
        DeviceBusiness deviceBusiness = new DeviceBusiness();
        deviceBusiness.setBusinessName(jsonObject.getStr("name"));
        deviceBusinessMapper.update(deviceBusiness,new QueryWrapper<DeviceBusiness>().eq("business_id",jsonObject.getStr("id")));
        //修改报警日志表
        DeviceAlarmLog deviceAlarmLog = new DeviceAlarmLog();
        deviceAlarmLog.setBusinessName(jsonObject.getStr("name"));
        deviceAlarmLogMapper.update(deviceAlarmLog,new QueryWrapper<DeviceAlarmLog>().eq("business_id",jsonObject.getStr("id")));
        return RespEntity.success();
    }

    /**
     * 产品列表
     * @param jsonParam
     * @return
     */
    public RespEntity productList(JSONObject jsonParam){

        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        List<Product> productList = productMapper.selectList(new QueryWrapper<Product>().eq("type",jsonParam.getStr("type")).orderByAsc("sortid"));
        return RespEntity.success(productList);
    }

    /**
     * 涛思
     * @param jsonParam
     * @return
     */
    public RespEntity getDeviceNormalLogAll1(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
//        List<DeviceBusiness> deviceBusinessList = deviceBusinessMapper.selectList(new QueryWrapper<DeviceBusiness>().eq("device_classify","4"));
//        for(DeviceBusiness deviceBusiness : deviceBusinessList){
//            int start = 1;
//            int end = 0;
//            jsonParam.put("deviceIdTable","iot_"+deviceBusiness.getId().replace("-",""));
//            jsonParam.put("businessId",deviceBusiness.getBusinessId());
//            while(true){
//                end = end + 1000;
//                //查询
//                jsonParam.put("start",start);
//                jsonParam.put("end",end);
//                List<Map<String,Object>> list = deviceNormalLogMapper.getDeviceNormalLogAll(jsonParam);
//                if(list.isEmpty()){
//                    break;
//                }
//                //rest调用涛思
//                jsonParam.put("list",list);
//                String domain = "http://101.201.140.249:8108/sequential/deviceNormalLogGas/insert";
//                String xml =  HttpUtil.post(domain,jsonParam.toJSONString(1));
//                start = start + 1000;
//                System.out.println(xml);
//            }
//            break;
//        }
        taosi(jsonParam,"1");
        //taosi(jsonParam,"2");
        //taosi(jsonParam,"4");


        return RespEntity.success();
    }
    public void taosi(JSONObject jsonParam, String deviceClassify){
        jsonParam.put("deviceClassify",deviceClassify);
        List<Map<String, Object>> list = deviceNormalLogMapper.getDeviceNormalLogAll(jsonParam);
        String domain = "";
        Map<String, String> fieldMap = new HashMap<>();
        if(deviceClassify.equals("1")){
            domain = "http://127.0.0.1:8108/sequential/deviceNormalLogElectricFire/insert";
            fieldMap = getFieldMap();

        }
        if(deviceClassify.equals("2")){
            domain = "http://127.0.0.1:8108/sequential/deviceNormalLogFireWater/insert";
        }
        if(deviceClassify.equals("4")){
            domain = "http://127.0.0.1:8108/sequential/deviceNormalLogGas/insert";
        }
        for(Map<String, Object> map : list){
            JSONObject jsonObject = new JSONObject();
            Set<String> set = map.keySet();
            for(String key : set){
                if(key.equals("deviceId")){
                    jsonObject.put("deviceId",map.get(key));
                    jsonObject.put("deviceIdTable","iot_" + map.get(key).toString().replace("-",""));
                }else{
                    if(fieldMap.containsKey(key)){
                        jsonObject.put(fieldMap.get(key),map.get(key));
                    }else{
                        jsonObject.put(key,map.get(key));
                    }
                }
            }
            jsonObject.put("time", Timestamp.valueOf(map.get("times").toString()));
            //rest调用涛思
            String xml =  HttpUtil.post(domain,jsonObject.toJSONString(1));
            System.out.println(xml);
        }
    }

    /**
     * 涛思
     * @param jsonParam
     * @return
     */
    public void taosi2(JSONObject jsonParam, String deviceClassify){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        List<DeviceBusiness> deviceBusinessList = deviceBusinessMapper.selectList(new QueryWrapper<DeviceBusiness>().eq("device_classify",deviceClassify));
        String domain = "";
        int index = 100;
        Map<String, String> fieldMap = new HashMap<>();
        if(deviceClassify.equals("1")){
            domain = "http://101.201.140.249:8108/sequential/deviceNormalLogElectricFire/insertBatch";
            fieldMap = getFieldMap();
            index = 50;
        }
        if(deviceClassify.equals("2")){
            domain = "http://127.0.0.1:8108/sequential/deviceNormalLogFireWater/insertBatch";
        }
        if(deviceClassify.equals("4")){
            domain = "http://101.201.140.249:8108/sequential/deviceNormalLogGas/insertBatch";
        }
        //jsonParam.put("deviceClassify",deviceClassify);
        //List<Map<String,Object>> list = deviceNormalLogMapper.getDeviceNormalLogAlls(jsonParam);
        for(DeviceBusiness deviceBusiness : deviceBusinessList){
            jsonParam.put("deviceId",deviceBusiness.getId());
            List<Map<String, Object>> listNew = deviceNormalLogMapper.getDeviceNormalLogAlls(jsonParam);
            List<Map<String, Object>> listNew1 = new ArrayList<>();
            if(deviceClassify.equals("1")){
                for(Map<String, Object> map : listNew){
                    Map<String, Object> map1 = new HashMap<>();
                    map1.put("time", Timestamp.valueOf(map.get("times").toString()));
                    Set<String> set = map.keySet();
                    for(String key : set){
                        if(fieldMap.containsKey(key)){
                            map1.put(fieldMap.get(key),map.get(key));
                        }else{
                            map1.put(key,map.get(key));
                        }
                    }
                    listNew1.add(map1);
                }
                listNew = listNew1;
            }else{
                for(Map<String, Object> map : listNew){
                    map.put("time", Timestamp.valueOf(map.get("times").toString()));
                }
            }
//            for(Map<String,Object> map : list){
//                if(deviceBusiness.getId().equals(map.get("deviceId").toString())){
//                    listNew.add(map);
//                }
//            }
            int start = 0;
            int end = 0;
            jsonParam.put("deviceIdTable","iot_"+deviceBusiness.getId().replace("-",""));
            jsonParam.put("businessId",deviceBusiness.getBusinessId());

            while(true){
                end = end + index;
                //查询
                jsonParam.put("start",start);
                jsonParam.put("end",end);
                List<Map<String, Object>> listNew2 = getMapList(listNew,start,end);
                if(listNew2.isEmpty()){
                    break;
                }
                //rest调用涛思
                jsonParam.put("list",listNew2);
                String xml =  HttpUtil.post(domain,jsonParam.toJSONString(1));
                start = start + index;
                System.out.println(xml);
            }
        }
    }

    /**
     * 设备号绑定openid
     * @param jsonParam
     * @return
     */
    public RespEntity deviceWechat(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        int deviceNumeber  = deviceBusinessMapper.selectCount(new QueryWrapper<DeviceBusiness>().eq("number",jsonParam.getStr("number")));
        if (deviceNumeber<=0){
            return RespEntity.fail("设备不存在!");
        }
        //查询设备号是否绑定
        int count = deviceWeChatMapper.selectCount(new QueryWrapper<DeviceWeChat>().eq("number",jsonParam.getStr("number")).eq("openid",jsonParam.getStr("openid")));
        if (count<=0){
            DeviceWeChat deviceWeChat = new DeviceWeChat();
            deviceWeChat.setNumber(jsonParam.getStr("number"));
            deviceWeChat.setOpenid(jsonParam.getStr("openid"));
            //设备绑定openid
            deviceWeChatMapper.insert(deviceWeChat);
        }
        return RespEntity.success();
    }
    public List<Map<String, Object>> getMapList(List<Map<String, Object>> listNew, int start, int end){
        int size = listNew.size();
        List<Map<String, Object>> listNew2 = new ArrayList<>();
        if(start >= size){
            return new ArrayList<>();
        }else{
            if(end > size){
                end = size;
            }
        }
        listNew2 = listNew.subList(start,end);
        return listNew2;
    }

    /**
     * 获取AiBox的视频流
     * @param jsonParam
     * @return
     */
    public RespEntity getRtmp(JSONObject jsonParam)throws UnsupportedEncodingException {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //查询设备详情
        DeviceBusiness deviceBusiness = deviceBusinessMapper.selectOne(new QueryWrapper<DeviceBusiness>().eq("number",jsonParam.getStr("number")));
        if (deviceBusiness == null||deviceBusiness.getProductKey()==null){
            return RespEntity.fail("设备号不存在!");
        }
//        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", "LTAI4FuyYyG4NhCy9gVuuBnV", "FLHWiYBr84G2wnYIS1shfFeOUXKGrE");
//        IAcsClient client = new DefaultAcsClient(profile);
//        CommonRequest request = new CommonRequest();
//        request.setMethod(MethodType.POST);
//        request.setDomain("iot.cn-shanghai.aliyuncs.com");
//        request.setVersion("2018-01-20");
//        request.setAction("QueryDeviceDetail");
//        request.putQueryParameter("RegionId", "cn-shanghai");
//        request.putQueryParameter("ProductKey", "g03qzG1uCAS");
//        request.putQueryParameter("DeviceName",jsonParam.getStr("number"));
//        try {
//            CommonResponse response = client.getCommonResponse(request);
//            System.out.println("++++queryDeviceDetail+++++++:"+response.getData());
//            JSONObject jsonObject = videoUrl(JSONUtil.parseObj(response));
//            //rtmp数据
//            JSONObject data = jsonObject.getJSONObject("data");
//            JSONObject Data = data.getJSONObject("Data");
//            String rtmp = Data.getStr("Path");
//            return RespEntity.success(rtmp);
//        } catch (ServerException e) {
//            e.printStackTrace();
//        } catch (ClientException e) {
//            e.printStackTrace();
//        }
        IoTApiClientBuilderParams builderParams = new IoTApiClientBuilderParams();
        builderParams.setAppKey("29503594");
        builderParams.setAppSecret("d722c6056a2a22d18e6c3272321d13a6");
        SyncApiClient syncClient = new SyncApiClient(builderParams);

        IoTApiRequest request = new IoTApiRequest();
        //设置api的版本
        request.setApiVer("0.1.6");
        //设置参数
        request.putParam("productKey", "g03qzG1uCAS");
        request.putParam("deviceName", jsonParam.getStr("number"));
        //请求参数域名、path、request
        String host = "iot-citylink-ca16.iot-api-gateway.cn-shanghai.iothub.aliyuncs.com";
        String path = "/device/vision/stream/query";

        try {
            ApiResponse response = syncClient.postBody(host, path, request);
            JSONObject jsonObject = JSONUtil.parseObj(new String(response.getBody()));
            System.out.println("....."+jsonObject.toString());
            //rtmp数据
            JSONObject data = jsonObject.getJSONObject("data");
            String rtmp = data.getStr("path");
            return RespEntity.success(rtmp);
        }catch (Exception e){
            return RespEntity.success("");
        }
    }
    /**
     * 获取海康控梯的Rtsp视频流
     * @param jsonParam
     * @return
     */
    public RespEntity getHKRtsp(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //查询设备详情
        DeviceBusiness deviceBusiness = deviceBusinessMapper.selectOne(new QueryWrapper<DeviceBusiness>().eq("number", jsonParam.getStr("number")));
        if (deviceBusiness == null || deviceBusiness.getProductKey() == null) {
            return RespEntity.fail("设备号不存在!");
        }
        String result = HikvisionInterfaceCall.GetCameraPreviewURL(jsonParam.getStr("number"),"/api/video/v2/cameras/previewURLs","rtsp");
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //rtmp数据
        JSONObject data = jsonObject.getJSONObject("data");
        String rtsp = data.getStr("url");
        return RespEntity.success(rtsp);
    }
    /**
     * 获取海康控梯录像回放Rtsp
     * @param jsonParam
     * @return
     */
    public RespEntity getHKPlayBackRtsp(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //查询设备详情
        DeviceBusiness deviceBusiness = deviceBusinessMapper.selectOne(new QueryWrapper<DeviceBusiness>().eq("number", jsonParam.getStr("number")));
        if (deviceBusiness == null || deviceBusiness.getProductKey() == null) {
            return RespEntity.fail("设备号不存在!");
        }
        String result = HikvisionInterfaceCall.GetHKPlayBackURL(jsonParam.getStr("number"),"/api/video/v2/cameras/playbackURLs","rtsp",jsonParam.getStr("beginTime"),jsonParam.getStr("endTime"));
        JSONObject jsonObject = JSONUtil.parseObj(result);
        JSONObject data = jsonObject.getJSONObject("data");
        String rtsp = data.getStr("url");
        return RespEntity.success(rtsp);
    }
    /**
     * 获取海康控梯录像回放Rtmp
     * @param jsonParam
     * @return
     */
    public RespEntity getHKPlayBackRtmp(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //查询设备详情
        DeviceBusiness deviceBusiness = deviceBusinessMapper.selectOne(new QueryWrapper<DeviceBusiness>().eq("number", jsonParam.getStr("number")));
        if (deviceBusiness == null || deviceBusiness.getProductKey() == null) {
            return RespEntity.fail("设备号不存在!");
        }
        //转换后开始时间
        String bt = StringToIos8601(jsonParam.getStr("beginTime"));
        //转换后结束时间
        String et = StringToIos8601(jsonParam.getStr("endTime"));
        String result = HikvisionInterfaceCall.GetHKPlayBackURL(jsonParam.getStr("number"),"/api/video/v2/cameras/playbackURLs?beginTime="+bt+"&endTime="+et,"rtmp",jsonParam.getStr("beginTime"),jsonParam.getStr("endTime"));
        JSONObject jsonObject = JSONUtil.parseObj(result);
        JSONObject data = jsonObject.getJSONObject("data");
        String rtsp = data.getStr("url");
        return RespEntity.success(rtsp);
    }
    /**
     * 获取海康控梯的Rtmp视频流
     * @param jsonParam
     * @return
     */
    public RespEntity getHKRtmp(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //查询设备详情
        DeviceBusiness deviceBusiness = deviceBusinessMapper.selectOne(new QueryWrapper<DeviceBusiness>().eq("number", jsonParam.getStr("number")));
        if (deviceBusiness == null || deviceBusiness.getProductKey() == null) {
            return RespEntity.fail("设备号不存在!");
        }
        String result = HikvisionInterfaceCall.GetCameraPreviewURL(jsonParam.getStr("number"),"/api/video/v2/cameras/previewURLs","rtmp");
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //rtmp数据
        JSONObject data = jsonObject.getJSONObject("data");
        String rtsp = data.getStr("url");
        return RespEntity.success(rtsp);
    }
    /**
     * @Author YangYu
     * @Description 获取视频流
     * @Date Created in 9:56 2023/3/6
     * @Param [jsonParam]
     */

    public RespEntity getVideoStream(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //查询设备详情
        DeviceBusiness deviceBusiness = deviceBusinessMapper.selectOne(new QueryWrapper<DeviceBusiness>().eq("number", jsonParam.getStr("number")));
        if (deviceBusiness == null || deviceBusiness.getProductId() == null) {
            return RespEntity.fail("设备号不存在!");
        }
        //视频流
        String videoStream = "";
        //海康
        if (deviceBusiness.getProductId().equals("6014") || deviceBusiness.getProductId().equals("6016") || deviceBusiness.getProductId().equals("6001")){
            if (deviceBusiness.getPlayType().equals("01")){
                String result = HikvisionInterfaceCall.GetCameraPreviewURL(jsonParam.getStr("number"),"/api/video/v2/cameras/previewURLs","rtmp");
                JSONObject jsonObject = JSONUtil.parseObj(result);
                //rtmp数据
                JSONObject data = jsonObject.getJSONObject("data");
                videoStream = data.getStr("url");
            }else if (deviceBusiness.getPlayType().equals("02")){
                String result = HikvisionInterfaceCall.GetCameraPreviewURL(jsonParam.getStr("number"),"/api/video/v2/cameras/previewURLs","hls");
                JSONObject jsonObject = JSONUtil.parseObj(result);
                //hls数据
                JSONObject data = jsonObject.getJSONObject("data");
                videoStream = data.getStr("url");
            }
            //获取SRS视频流地址
        }else if (deviceBusiness.getProductId().equals("6017")){
            jsonParam.put("device_id",deviceBusiness.getNumber().substring(0,36));
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("number",deviceBusiness.getNumber());
            String cmd = "curl 127.0.0.1:5003/device/start_video -X POST -d '"+jsonObject+"' --header \"Content-Type: application/json\"";
            jsonParam.put("cmd",cmd);
            rest_tcp_push(jsonParam, "tcp_server_push", "tcp_server_push_cmd", "tcp");
            String addr = ConfigKit.getStr("video_play", "config");
            videoStream = addr+"/srs-flv-push/live/"+deviceBusiness.getNumber()+".flv";
        }else if (deviceBusiness.getProductId().equals("6018") || deviceBusiness.getProductId().equals("6019")){
            JSONObject jsonObject = restIotTokenPlay("iotPost","play","iot_post","eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6Ijk2MmQ3MGIyLTY2NmYtNGZkNi1iN2IyLTRkNTA0YWYwMzI1NyJ9.055zsyU0-7weD3sLcZ5n_F_UWsTo9H7V7MHf5RB1nDsz6jNk2UY7NQckohycN6eyQwOQ6RMgHGl8oiR1RRzIlQ","/"+deviceBusiness.getNumber()+"/"+deviceBusiness.getNumber());
            if (jsonObject.getInt("code") == 200){
                String[] fmp4s = jsonObject.getJSONObject("data").getStr("fmp4").split("6082");
                videoStream = "https://aq.wisdiot.com/iot-gb-mp4"+fmp4s[1];
            }
        }
        return RespEntity.success(videoStream);
    }

    /**
     * @Author YangYu
     * @Description 关闭视频流
     * @Date Created in 9:56 2023/3/6
     * @Param [jsonParam]
     */

    public RespEntity closeVideoStream(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //查询设备详情
        DeviceBusiness deviceBusiness = deviceBusinessMapper.selectOne(new QueryWrapper<DeviceBusiness>().eq("number", jsonParam.getStr("number")));
        if (deviceBusiness == null || deviceBusiness.getProductId() == null) {
            return RespEntity.fail("设备号不存在!");
        }

        //海康
        if (deviceBusiness.getProductId().equals("6014") || deviceBusiness.getProductId().equals("6016") || deviceBusiness.getProductId().equals("6001")){

        }else if (deviceBusiness.getProductId().equals("6017")){
            jsonParam.put("device_id",deviceBusiness.getNumber().substring(0,36));
            jsonParam.put("cmd","docker stop "+deviceBusiness.getNumber());
            rest_tcp_push(jsonParam, "tcp_server_push", "tcp_server_push_cmd", "tcp");
        }else if (deviceBusiness.getProductId().equals("6018") || deviceBusiness.getProductId().equals("6019")){
            JSONObject jsonObject = restIotTokenPlay("iotPost","closeStream","iot_post","eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjkxZGQ0YzEzLTQzMzItNDRkYy04MGU4LTdlNWE5YmFhZDY2NSJ9.0MiTNYXmt5cjxZR7zbHN_mJEVvKH0uHeFCsPl0y5-3qDnxTJzk6UBdCY552d7g3INOgdAW0R_cPTjJD2j0PqeQ","/"+deviceBusiness.getNumber()+"/"+deviceBusiness.getNumber()+"/gb_play_"+deviceBusiness.getNumber()+"_"+deviceBusiness.getNumber());
        }
        return RespEntity.success();
    }


    /**
     * 获取海康控梯的语音流地址
     * @param jsonParam
     * @return
     */
    public RespEntity getHKTalkRtsp(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //查询设备详情
        DeviceBusiness deviceBusiness = deviceBusinessMapper.selectOne(new QueryWrapper<DeviceBusiness>().eq("number", jsonParam.getStr("number")));
        if (deviceBusiness == null || deviceBusiness.getProductKey() == null) {
            return RespEntity.fail("设备号不存在!");
        }
        String result = HikvisionInterfaceCall.GetCameraPreviewURL(jsonParam.getStr("number"),"/api/video/v1/cameras/talkURLs","rtsp");
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //rtmp数据
        JSONObject data = jsonObject.getJSONObject("data");
        String rtsp = data.getStr("url");
        return RespEntity.success(rtsp);
    }

    /**
     * String类型的时间(yyyy-MM-dd HH:mm:ss)转换成IOS-8601格式
     * @param data
     * @return
     */
    public static String StringToIos8601(String data) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dt1 = LocalDateTime.parse(data, dateTimeFormatter);
        ZoneOffset offset = ZoneOffset.of("+08:00");
        OffsetDateTime date = OffsetDateTime.of(dt1, offset);
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
        String datas = date.format(formatter2);
        return datas;
    }


    /**
     * 根据AiBox摄像头IotId查询视频流
     * @param jsonParam
     * @return
     */
    public JSONObject videoUrl(JSONObject jsonParam){
        //AiBox设备详情数据
        JSONObject data = jsonParam.getJSONObject("data");
        JSONObject Data = data.getJSONObject("Data");
        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", "LTAI4FuyYyG4NhCy9gVuuBnV", "FLHWiYBr84G2wnYIS1shfFeOUXKGrE");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("linkvisual.cn-shanghai.aliyuncs.com");
        request.setVersion("2018-01-20");
        request.setAction("QueryLiveStreaming");
        request.putQueryParameter("RegionId", "cn-shanghai");
        request.putQueryParameter("IotId", Data.getStr("IotId"));
        try {
            CommonResponse response = client.getCommonResponse(request);
            JSONObject jsonObject = JSONUtil.parseObj(response);
            return jsonObject;
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @Author YangYu
     * @Description 更新派安烟感网关设备状态
     * @Date Created in 10:21 2021/10/29
     * @Param [jsonParam]
     */

    public RespEntity updateGatewaysSmokeState(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        DeviceBusiness deviceBusiness = new DeviceBusiness();
        UpdateWrapper<DeviceBusiness> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("number",jsonParam.getStr("number")).set("currentstate", "3").set("normal_update_time", DateUtil.now());
        deviceBusinessMapper.update(deviceBusiness,updateWrapper);
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 更新海康梯控摄像头（门禁参数）
     * @Date Created in 15:52 2021/12/7
     * @Param [jsonParam]
     */
    public RespEntity updateHKCamera(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        if (StrUtil.isBlank(jsonParam.getStr("number"))){
            return RespEntity.fail("number不能为空!");
        }else {
            JSONObject jsonBody = new JSONObject();
            jsonBody.put("resourceType","ioOut");
            jsonBody.put("pageNo",1);
            jsonBody.put("pageSize",300);
            jsonBody.put("orderBy","name");
            jsonBody.put("orderType","desc");
            JSONArray jsonArray = new JSONArray();
            JSONObject expressions = new JSONObject();
            expressions.put("key","parentIndexCode");
            expressions.put("operator",0);
            JSONArray values = new JSONArray();
            values.add(jsonParam.getStr("deviceCode"));
            expressions.put("values",values);
            jsonArray.add(expressions);
            jsonBody.put("expressions",jsonArray);
            //调用海康接口
            String result = HikvisionInterfaceCall.eventSubscriptionsHK("/api/irds/v2/resource/resourcesByParams",jsonBody);
            JSONObject resultJson = JSONUtil.parseObj(result);
            JSONObject data = resultJson.getJSONObject("data");
            JSONArray list = data.getJSONArray("list");
            JSONObject listJson = (JSONObject)list.get(0);
            DeviceBusiness deviceBusiness = new DeviceBusiness();
            deviceBusinessMapper.update(deviceBusiness,new UpdateWrapper<DeviceBusiness>().eq("number",jsonParam.getStr("number")).set("device_index_code",listJson.getStr("parentIndexCode")).set("channel_index_code",listJson.getStr("indexCode")));
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 海康梯控远程关门
     * @Date Created in 9:41 2021/12/8
     * @Param [jsonParam]
     */

    public RespEntity remoteClosing(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        //校验参数是否为null
        if (StrUtil.isBlank(jsonParam.getStr("deviceIndexCode")) || StrUtil.isBlank(jsonParam.getStr("channelIndexCode"))){
            return RespEntity.fail("deviceIndexCode和channelIndexCode不能为空!");
        }else {
            JSONObject jsonBody = new JSONObject();
            jsonBody.put("deviceIndexCode",jsonParam.getStr("deviceIndexCode"));
            jsonBody.put("channelIndexCode",jsonParam.getStr("channelIndexCode"));
            //调用海康接口
            asyncService.remoteClosing(jsonBody);
//            String result = HikvisionInterfaceCall.eventSubscriptionsHK("/api/edp/v1/setAlarmOut",jsonBody);
//            JSONObject resultJson = JSONUtil.parseObj(result);
//            if (!resultJson.getStr("code").equals("0")){
//                return RespEntity.fail(resultJson.getStr("msg"));
//            }
        }
        return RespEntity.success();
    }
    /**
     * 烟感设备更新祥云设备id
     * @param jsonParam
     * @return
     */
    public RespEntity termIdUpdate(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        DeviceBusiness deviceBusiness = deviceBusinessMapper.selectOne(new QueryWrapper<DeviceBusiness>().eq("number",jsonParam.getStr("number")));
        //判断TermId是否为空
        if (deviceBusiness.getTermId()==null|| "".equals(deviceBusiness.getTermId())){
            deviceBusiness.setTermId(jsonParam.getStr("termId"));
            deviceBusinessMapper.update(deviceBusiness,new QueryWrapper<DeviceBusiness>().eq("number",jsonParam.getStr("number")));
        }else if (!deviceBusiness.getTermId().equals(jsonParam.getStr("termId"))){
            deviceBusiness.setTermId(jsonParam.getStr("termId"));
            deviceBusinessMapper.update(deviceBusiness,new QueryWrapper<DeviceBusiness>().eq("number",jsonParam.getStr("number")));
        }
        return RespEntity.success();
    }
    /**
     * 卸油证据链分页列表
     * @param jsonParam
     * @return
     */
    public RespEntity getChainOfEvidencePageList(JSONObject jsonParam){
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        Page<ChainofcvidenceUploadFile> page = new Page<>(jsonParam.getInt("page"),jsonParam.getInt("limit"));
        IPage<ChainofcvidenceUploadFile> iPage =  chainofcvidenceUploadFileMapper.getChainOfEvidencePageList(page, jsonParam);
        List<ChainofcvidenceUploadFile> records = iPage.getRecords();
        Map<String, Object> data = new HashMap<>();
        data.put("totalSize", iPage.getTotal());
        data.put("pages", iPage.getPages());
        data.put("pageSize", jsonParam.getInt("limit"));
        data.put("Items",records);
        data.put("currentPage",jsonParam.getInt("page"));
        data.put("currentSize",jsonParam.getInt("limit"));
        return RespEntity.success(data);
    }

    /**
     * @Author YangYu
     * @Description 空开下发指令
     * @Date Created in 10:37 2021/12/1
     * @Param [jsonParam]0000 00FF
     */

    public RespEntity openIssued(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        String number = jsonParam.getStr("number");
        String add = number.substring(number.length()-2,number.length());
        add = intToHex(add);
        String code = "";
        if (jsonParam.getStr("type").equals("1")){
            code = add+"1900010000";
        }else {
            code = add+"19000100ff";
        }
        String crc = ByteUtil.getCRC(ByteUtil.hexToBytes(code));
        //下发指令
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("number",number.substring(0,16));
        jsonObject.put("code",code+crc.substring(2,4)+crc.substring(0,2)+"0d0a0d0a");
        rest(jsonObject, "openTcpClient", "openIssued", "tcp", "POST");
        updateOpeningState(jsonParam);
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 更新空开设备分闸状态
     * @Date Created in 15:35 2021/12/1
     * @Param [jsonParam]
     */

    public RespEntity updateOpeningState(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        String number = jsonParam.getStr("number");
        DeviceBusiness deviceBusiness = new DeviceBusiness();
        if (StrUtil.isBlank(number)){
            return RespEntity.fail("number不能为空!");
        }else {
            if (jsonParam.containsKey("type")){
                deviceBusinessMapper.update(deviceBusiness,new UpdateWrapper<DeviceBusiness>().eq("number",number).set("opening_state",jsonParam.getStr("type")));
            }else {
                deviceBusinessMapper.update(deviceBusiness,new UpdateWrapper<DeviceBusiness>().eq("number",number).set("opening_state",jsonParam.getStr("openingState")));
            }
        }
        return RespEntity.success();
    }


    /**
     * @Author YangYu
     * @Description 十进制转十六进制
     * @Date Created in 14:47 2021/12/1
     * @Param [hex]
     */

    public String intToHex(String hex){
        String str = Integer.toHexString(Integer.parseInt(hex));
        if (str.length() <2){
            str ="0"+str;
        }
        return str;
    }

    /**
     * 涛思
     * @param jsonParam
     * @return
     */
    public RespEntity getDeviceNormalLogAll2(JSONObject jsonParam){
        //taosi2(jsonParam,"1");
        taosi2(jsonParam,"2");
        //taosi2(jsonParam,"4");
        return RespEntity.success();
    }

    //获取正常二级数据项和正常数据日志字段的映射
    public Map<String, String> getFieldMap() {
        Map<String, String> map = new HashMap<>();//组装数据
        //获取获取正常二级数据项和正常数据日志字段的映射关系列表
        List<ItemLogFieldMapping> list = itemLogFieldMappingMapper.selectList(new QueryWrapper<>());
        for (ItemLogFieldMapping mapping : list) {
            map.put(mapping.getNoUnderLineName(), mapping.getLogValueName());
        }
        return map;
    }

    /**
     * 消防物联网系统列表
     * @return
     */
    public RespEntity getIotSystemList(){
        List<IotSystem> list = iotSystemMapper.selectList(new QueryWrapper<IotSystem>());
        return RespEntity.success(list);
    }

    /**
     * 修改离线设备状态
     * @param jsonParam
     * @return
     */
    public RespEntity updateToOff(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        logger.info("----------------updateToOff离线------------------");
        deviceBusinessMapper.updateToOffForFire(new JSONObject());
        deviceBusinessMapper.updateToOffForWater(new JSONObject());
        deviceBusinessMapper.updateToOffForGas(new JSONObject());
        deviceBusinessMapper.updateToOffForSmoke(new JSONObject());
        deviceBusinessMapper.updateToOffForHx100(new JSONObject());
        deviceBusinessMapper.updateToOffForWaterPump(new JSONObject());
        deviceBusinessMapper.updateToOffForWaterColumn(new JSONObject());
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 检索用户传输装置一分钟内没报警更新设备在线状态
     * @Date Created in 10:27 2022/2/8
     * @Param []
     */

    public RespEntity updateToHEX100(){
        List<String> list = deviceAlarmLogAutoNetworkTodayMapper.selectAlarmTodayList();
        DeviceBusiness deviceBusiness = new DeviceBusiness();
        if (list != null && list.size() != 0){
            for (String number : list){
                deviceBusinessMapper.update(deviceBusiness,new UpdateWrapper<DeviceBusiness>().eq("number",number).set("currentstate","1"));
            }
        }
        return RespEntity.success();
    }
    /**
     * @Author YangYu
     * @Description 修改水泵故障指示灯、手自动
     * @Date Created in 13:56 2022/5/24
     * @Param [jsonParam]
     */

    public RespEntity updateWaterPumpInfo(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        String number = jsonParam.getStr("number");
        DeviceBusiness deviceBusiness = new DeviceBusiness();
        deviceBusiness.setControlCabinetStatus(jsonParam.getStr("controlCabinetStatus"));
        deviceBusiness.setControlCabinetHandleStatus(jsonParam.getStr("controlCabinetHandleStatus"));
        int update = deviceBusinessMapper.update(deviceBusiness, new QueryWrapper<DeviceBusiness>().eq("number", number).eq("device_classify", "10"));
        if (update > 1) {
            return RespEntity.success();
        }
        return RespEntity.fail();
    }

    /**
     * @Author YangYu
     * @Description 设备接入统计（根据系统类型统计）
     * @Date Created in 13:57 2022/5/24
     * @Param [jsonParam]
     */

    public RespEntity deviceCount(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        HashMap<String, Object> date = new HashMap<>();
        int count = deviceBusinessMapper.selectCount(new QueryWrapper<DeviceBusiness>().like("all_id",homeId).eq("device_classify",jsonParam.getStr("deviceClassify")));
        date.put("count",count);
        return RespEntity.success(date);
    }

    /**
     * @Author YangYu
     * @Description 根据单位获取明厨亮灶设备列表
     * @Date Created in 15:40 2022/5/24
     * @Param [jsonParam]
     */

    public RespEntity getBrightKitchenDevice(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        List<DeviceBusiness> deviceBusinessList = deviceBusinessMapper.selectList(new QueryWrapper<DeviceBusiness>().eq("business_id",jsonParam.getStr("businessId")).eq("device_classify","16"));
        for (DeviceBusiness deviceBusiness : deviceBusinessList){
            List<DeviceBusinessVideoplayAddr> deviceBusinessVideoplayAddrList = deviceBusinessVideoplayAddrMapper.selectList(new QueryWrapper<DeviceBusinessVideoplayAddr>().eq("device_id",deviceBusiness.getId()));
            deviceBusiness.put("videoplayAdds",deviceBusinessVideoplayAddrList);
        }
        return RespEntity.success(deviceBusinessList);
    }
    /**
     * @Author YangYu
     * @Description 根据机构获取明厨亮灶设备列表
     * @Date Created in 15:40 2022/5/24
     * @Param [jsonParam]
     */

    public RespEntity getOrgBrightKitchenDevice(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        List<DeviceBusiness> deviceBusinessList = deviceBusinessMapper.selectList(new QueryWrapper<DeviceBusiness>().like("all_id",homeId).eq("device_classify","16"));
        for (DeviceBusiness deviceBusiness : deviceBusinessList){
            List<DeviceBusinessVideoplayAddr> deviceBusinessVideoplayAddrList = deviceBusinessVideoplayAddrMapper.selectList(new QueryWrapper<DeviceBusinessVideoplayAddr>().eq("device_id",deviceBusiness.getId()));
            deviceBusiness.put("videoplayAdds",deviceBusinessVideoplayAddrList);
        }
        return RespEntity.success(deviceBusinessList);
    }

    /**
     * @Author YangYu
     * @Description 加油站通道新增、编辑
     * @Date Created in 14:15 2022/10/13
     * @Param [jsonParam]
     */

    public RespEntity deviceChannelAddOrUpdate(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        DeviceChannel deviceChannel = new DeviceChannel();
        deviceChannel.setChannel(jsonParam.getStr("channel"));
        deviceChannel.setChannelCode(jsonParam.getStr("channelCode"));
        deviceChannel.setDeviceId(jsonParam.getStr("deviceId"));
        if (jsonParam.containsKey("id")){
            DeviceChannel deviceChannelOdl = deviceChannelMapper.selectById(jsonParam.getStr("id"));
            if (!deviceChannelOdl.getChannel().equals(jsonParam.getStr("channel"))){
                int i = deviceChannelMapper.selectCount(new QueryWrapper<DeviceChannel>().eq("device_id",jsonParam.getStr("deviceId")).eq("channel",jsonParam.getStr("channel")));
                if (i > 0){
                    return RespEntity.fail("通道已存在");
                }
            }
            deviceChannel.setId(jsonParam.getStr("id"));
            deviceChannelMapper.updateById(deviceChannel);
        }else {
            int i = deviceChannelMapper.selectCount(new QueryWrapper<DeviceChannel>().eq("device_id",jsonParam.getStr("deviceId")).eq("channel",jsonParam.getStr("channel")));
            if (i > 0){
                return RespEntity.fail("通道已存在");
            }
            deviceChannel.setId(UUID.randomUUID().toString());
            deviceChannelMapper.insert(deviceChannel);
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 加油站通道删除
     * @Date Created in 14:29 2022/10/13
     * @Param [jsonParam]
     */

    public RespEntity deviceChannelDel(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        if (StrUtil.isBlank(jsonParam.getStr("id"))){
            return RespEntity.fail("id不能为空");
        }
        deviceChannelMapper.deleteById(jsonParam.getStr("id"));
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 加油站通道列表
     * @Date Created in 14:32 2022/10/13
     * @Param [jsonParam]
     */

    public RespEntity deviceChannelList(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        List<DeviceChannel> deviceChannelList = deviceChannelMapper.selectList(new QueryWrapper<DeviceChannel>().eq("device_id",jsonParam.getStr("deviceId")));
        return RespEntity.success(deviceChannelList);
    }

    /**
     * @Author YangYu
     * @Description 设备与监控绑定
     * @Date Created in 14:15 2022/10/13
     * @Param [jsonParam]
     */

    public RespEntity deviceCameraBindingAddOrUpdate(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        //先删除绑定再添加
        deviceCameraBindingMapper.delete(new QueryWrapper<DeviceCameraBinding>().eq("device_id",jsonParam.getStr("deviceId")));
        JSONArray cameras = jsonParam.getJSONArray("cameras");
        DeviceCameraBinding deviceCameraBinding = new DeviceCameraBinding();
        for (Object obj : cameras){
            JSONObject jsonObject = (JSONObject) obj;
            deviceCameraBinding.setDeviceId(jsonParam.getStr("deviceId"));
            deviceCameraBinding.setCameraNumber(jsonObject.getStr("cameraNumber"));
            deviceCameraBinding.setCameraName(jsonObject.getStr("cameraName"));
            deviceCameraBindingMapper.insert(deviceCameraBinding);
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 设备与监控删除绑定
     * @Date Created in 14:40 2022/12/21
     * @Param [jsonParam]
     */

    public RespEntity deviceCameraBindingDel(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        if (StrUtil.isBlank(jsonParam.getStr("deviceId")) || StrUtil.isBlank(jsonParam.getStr("cameraNumber"))){
            return RespEntity.fail("deviceId和cameraNumber不能为空");
        }
        deviceCameraBindingMapper.delete(new QueryWrapper<DeviceCameraBinding>().eq("device_id",jsonParam.getStr("deviceId")).eq("camera_number",jsonParam.getStr("cameraNumber")));
        return RespEntity.success();
    }
    /**
     * @Author YangYu
     * @Description 设备与监控绑定列表
     * @Date Created in 14:41 2022/12/21
     * @Param [jsonParam]
     */

    public RespEntity deviceCameraBindingList(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        List<DeviceCameraBinding> list = deviceCameraBindingMapper.selectList(new QueryWrapper<DeviceCameraBinding>().eq("device_id",jsonParam.getStr("deviceId")));
        return RespEntity.success(list);
    }
    /**
     * @Author YangYu
     * @Description 电信AEP盛善电设备下发指令
     * @Date Created in 14:41 2022/12/21
     * @Param [jsonParam]
     */

    public RespEntity createCommand(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        String code = "";
        DeviceBusiness deviceBusiness = deviceBusinessMapper.selectOne(new QueryWrapper<DeviceBusiness>().eq("number",jsonParam.getStr("number")));
        //电闸状态：1闭合 2断开
        if (jsonParam.getStr("state").equals("1")){
            code = "16B1"+ByteUtil.stringToAscii(jsonParam.getStr("number"))+"00000000FF";
            deviceBusiness.setOpeningState("1");
        }else {
            code = "16B1"+ByteUtil.stringToAscii(jsonParam.getStr("number"))+"0000000000";
            deviceBusiness.setOpeningState("2");
        }
        if (StrUtil.isBlank(deviceBusiness.getTermId())){
            //盛善
            if (deviceBusiness.getProductId().equals("1001") || deviceBusiness.getProductId().equals("1005")){
                code = "FE0016"+code;
                code = code+getCrc(code);
                jsonParam.put("code",code);
                jsonParam.put("number",ByteUtil.stringToAscii(jsonParam.getStr("number")));
                rest(jsonParam, "tcpCommand", "tcpClient", "tcp", "POST");
            }
            //更新电闸状态
            deviceBusinessMapper.updateById(deviceBusiness);
        }else {
            jsonParam.put("code",code);
            //获取Base64编码
            RespEntity rest = rest(jsonParam, "aepCommand", "getBase64", "python", "GET");
            JSONObject dataRest = (JSONObject)rest.getData();
            String base64 = dataRest.getStr("data");
            base64 = base64.substring(0,base64.length()-2);
            System.out.println(base64);
            //下发json指令
            JSONObject json = new JSONObject();
            //指令
            JSONObject command = new JSONObject();
            //指令参数
            JSONObject paras = new JSONObject();
            paras.put("Header",254);
            paras.put("Len",22);
            paras.put("CRC",ByteUtil.hexToInt(getCrc(code)));
            paras.put("Data",base64);
            command.put("serviceId","DataPackage");
            command.put("method","Control");
            command.put("paras",paras);
            json.put("command",command);
            json.put("deviceId",deviceBusiness.getTermId());
            json.put("operator","hltong168");
            json.put("productId",15545011);
            json.put("ttl",7200);
            json.put("level",1);
            rest(json, "aepCommand", "createCommand", "python", "POST");
            //更新电闸状态
            deviceBusinessMapper.updateById(deviceBusiness);
        }
        return RespEntity.success();
    }
    public static String getCrc(String code){
        String crc = ByteUtil.getCRC(ByteUtil.hex2byte(code));
        //08bf
        crc = crc.substring(2,4)+crc.substring(0,2);
        return crc;
    }


    /**
     * @Author YangYu
     * @Description 电能数据(单个设备查询)
     * @Date Created in 14:50 2023/3/2
     * @Param [jsonParam]
     */

    public RespEntity electricEnergyList(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

//        List<JSONObject> datas = new ArrayList<>();
//        List<JSONObject> table =  getTableList();
//
//        for (JSONObject jsonObject : table){
//            jsonObject.put("number",jsonParam.getStr("number"));
//            Map<String, Object> map = deviceNormalLogMapper.getElectricEnergy(jsonObject);
//            JSONObject data = new JSONObject();
//            data.put("date",jsonObject.getStr("date"));
//            double d = Double.parseDouble(map.get("A").toString())-Double.parseDouble(map.get("B").toString());
//            data.put("electricEnergy",String.format("%.2f",d));
//            datas.add(data);
//        }
        List<Map<String, Object>> map = deviceNormalLogMapper.electricEnergyList(jsonParam);
        return RespEntity.success(map);
    }

    public static List<JSONObject> getTableList(){
        List<String> oneTimeList = DayUtil.getPastDateList(6);
        oneTimeList.add(0,DayUtil.getTodayForStatistics("yyyy-MM-dd"));
        List<JSONObject> list = new ArrayList<>();
        List<String> twoTimeList = DayUtil.getPastDateList(7);
        for (String str1 : oneTimeList){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("date",str1);
            jsonObject.put("oneTable","device_normal_log_electric_fire_"+str1.replace("-",""));
            list.add(jsonObject);
        }
        int i = 0;
        for (String str2 : twoTimeList){
            JSONObject jsonObject = list.get(i);
            jsonObject.put("twoTable","device_normal_log_electric_fire_"+str2.replace("-",""));
            i= i+1;
        }
        return list;
    }

    /**
     * @Author YangYu
     * @Description 电正常数据详情
     * @Date Created in 14:50 2023/3/2
     * @Param [jsonParam]
     */

    public RespEntity getElectricDataDetails(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        if (jsonParam.getStr("deviceClassify").equals("22")){
            jsonParam.put("table","device_normal_log_charging_station_"+DayUtil.getToday());
        }else {
            jsonParam.put("table","device_normal_log_electric_fire_"+DayUtil.getToday());
        }
        Map<String, Object> map = deviceNormalLogMapper.getElectricDataDetails(jsonParam);
        return RespEntity.success(map);
    }

    /**
     * @Author YangYu
     * @Description 小程序、APP统计模块
     * @Date Created in 14:50 2023/3/2
     * @Param [jsonParam]
     */

    public RespEntity getDeviceCountApp(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        if (!userType.equals("1"))return RespEntity.fail("不是机构账户");
        if (jsonParam.containsKey("orgId") && StrUtil.isNotBlank(jsonParam.getStr("orgId"))) {
            jsonParam.put("orgId", jsonParam.getStr("orgId"));
        } else {
            jsonParam.put("orgId", homeId);
        }
        List<DeviceBusiness> deviceStateCountList = deviceBusinessMapper.getDeviceStateCount(jsonParam);
        JSONObject deviceStateCount = new JSONObject();
        // 设备总数
        int deviceCount = 0;
        // 预警设备总数
        int alarmDeviceCount = 0;
        // 故障设备总数
        int hitchDeviceCount = 0;
        // 离线设备总数
        int offlineDeviceCount = 0;
        for (DeviceBusiness deviceBusiness : deviceStateCountList){
            if (deviceBusiness.getCurrentstate().equals("1")){
                deviceCount = deviceCount+deviceBusiness.getInt("count");
            }else if (deviceBusiness.getCurrentstate().equals("2")){
                deviceCount = deviceCount+deviceBusiness.getInt("count");
                alarmDeviceCount = alarmDeviceCount+deviceBusiness.getInt("count");
            }else if (deviceBusiness.getCurrentstate().equals("3")){
                deviceCount = deviceCount+deviceBusiness.getInt("count");
                offlineDeviceCount = offlineDeviceCount+deviceBusiness.getInt("count");
            }else if (deviceBusiness.getCurrentstate().equals("4")){
                deviceCount = deviceCount+deviceBusiness.getInt("count");
                hitchDeviceCount = hitchDeviceCount+deviceBusiness.getInt("count");
            }
        }
        deviceStateCount.put("deviceCount",deviceCount);
        deviceStateCount.put("alarmDeviceCount",alarmDeviceCount);
        deviceStateCount.put("hitchDeviceCount",hitchDeviceCount);
        deviceStateCount.put("offlineDeviceCount",offlineDeviceCount);
        //各个系统类型的设备统计
        List<DeviceBusiness> deviceClassifyList = deviceBusinessMapper.getDeviceClassifyCount(jsonParam);
        // 电
        int electricDeviceCount = 0;
        // 水
        int waterDeviceCount = 0;
        // 烟感
        int smokeDeviceCount = 0;
        // 燃气
        int gasDeviceCount = 0;
        // 自动联网
        int autoDeviceCount = 0;
        // 慧眼识别
        int clairvoyantDeviceCount = 0;
        // 灭火器
        int extinguisherDeviceCount = 0;
        // 水泵
        int waterPumpDeviceCount = 0;
        // 加油站
        int gasStationDeviceCount = 0;
        // 梯控
        int ladderDeviceCount = 0;
        // 智慧水域
        int smartWatersDeviceCount = 0;
        // 可视视频
        int videoDeviceCount = 0;
        // 开关量
        int switchingDeviceCount = 0;
        JSONObject deviceClassifyCount = new JSONObject();
        for (DeviceBusiness deviceBusiness : deviceClassifyList){
            if (deviceBusiness.getDeviceClassify().equals("1")){
                electricDeviceCount = electricDeviceCount+deviceBusiness.getInt("count");
            }else if (deviceBusiness.getDeviceClassify().equals("2")){
                waterDeviceCount = waterDeviceCount+deviceBusiness.getInt("count");
            }else if (deviceBusiness.getDeviceClassify().equals("3")){
                smokeDeviceCount = smokeDeviceCount+deviceBusiness.getInt("count");
            }else if (deviceBusiness.getDeviceClassify().equals("4")){
                gasDeviceCount = gasDeviceCount+deviceBusiness.getInt("count");
            }else if (deviceBusiness.getDeviceClassify().equals("5")){
                autoDeviceCount = autoDeviceCount+deviceBusiness.getInt("count");
            }else if (deviceBusiness.getDeviceClassify().equals("6")){
                clairvoyantDeviceCount = clairvoyantDeviceCount+deviceBusiness.getInt("count");
            }else if (deviceBusiness.getDeviceClassify().equals("7")){
                extinguisherDeviceCount = extinguisherDeviceCount+deviceBusiness.getInt("count");
            }else if (deviceBusiness.getDeviceClassify().equals("10")){
                waterPumpDeviceCount = waterPumpDeviceCount+deviceBusiness.getInt("count");
            }else if (deviceBusiness.getDeviceClassify().equals("11")){
                gasStationDeviceCount = gasStationDeviceCount+deviceBusiness.getInt("count");
            }else if (deviceBusiness.getDeviceClassify().equals("12")){
                ladderDeviceCount = ladderDeviceCount+deviceBusiness.getInt("count");
            }else if (deviceBusiness.getDeviceClassify().equals("13")){
                smartWatersDeviceCount = smartWatersDeviceCount+deviceBusiness.getInt("count");
            }else if (deviceBusiness.getDeviceClassify().equals("15")){
                videoDeviceCount = videoDeviceCount+deviceBusiness.getInt("count");
            }else if (deviceBusiness.getDeviceClassify().equals("19")){
                switchingDeviceCount = switchingDeviceCount+deviceBusiness.getInt("count");
            }
        }
        deviceClassifyCount.put("electricDeviceCount",electricDeviceCount);
        deviceClassifyCount.put("waterDeviceCount",waterDeviceCount);
        deviceClassifyCount.put("smokeDeviceCount",smokeDeviceCount);
        deviceClassifyCount.put("gasDeviceCount",gasDeviceCount);
        deviceClassifyCount.put("autoDeviceCount",autoDeviceCount);
        deviceClassifyCount.put("clairvoyantDeviceCount",clairvoyantDeviceCount);
        deviceClassifyCount.put("extinguisherDeviceCount",extinguisherDeviceCount);
        deviceClassifyCount.put("waterPumpDeviceCount",waterPumpDeviceCount);
        deviceClassifyCount.put("gasStationDeviceCount",gasStationDeviceCount);
        deviceClassifyCount.put("ladderDeviceCount",ladderDeviceCount);
        deviceClassifyCount.put("smartWatersDeviceCount",smartWatersDeviceCount);
        deviceClassifyCount.put("videoDeviceCount",videoDeviceCount);
        deviceClassifyCount.put("switchingDeviceCount",switchingDeviceCount);
        //单位统计
        Integer count  = deviceBusinessMapper.getBusinessCount(jsonParam.getStr("orgId"));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("deviceStateCount",deviceStateCount);
        jsonObject.put("deviceClassifyCount",deviceClassifyCount);
        jsonObject.put("businessCount",count);
        return RespEntity.success(jsonObject);
    }

    public RespEntity deviceChildrenListPage(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        Page<DeviceBusiness> page = new Page<>(jsonParam.getInt("page"), jsonParam.getInt("limit"));
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");

        IPage<DeviceBusinessChildren> pageList = deviceBusinessChildrenMapper.deviceChildrenListPage(page, jsonParam);
        Map<String, Object> data = new HashMap<>();
        data.put("totalSize", pageList.getTotal());//总条数
        data.put("pageSize", pageList.getSize());//每页展示多少条
        data.put("currentPage", pageList.getCurrent());//当前页
        data.put("Items", pageList.getRecords());//数据
        data.put("pages", pageList.getPages());//总页数
        data.put("currentSize", pageList.getRecords().size());//当前页多少条
        return RespEntity.success(data);
    }

    /**
     * @Author YangYu
     * @Description 新增、编辑子设备
     * @Date Created in 10:00 2023/5/11
     * @Param [jsonParam]
     */

    public RespEntity deviceChildrenAddOrUpdate(JSONObject jsonParam) throws Exception {

        //网关详情
        DeviceBusiness deviceBusiness = deviceBusinessMapper.selectOne(new QueryWrapper<DeviceBusiness>().eq("number",jsonParam.getStr("transDeviceCode")));
        String id = "";
        if (jsonParam.containsKey("id")){
            id = jsonParam.getStr("id");
        }else {
            id = UUID.randomUUID().toString();
            //先删除再更新
            deviceBusinessChildrenMapper.deleteById(id);
        }
        DeviceBusinessChildren deviceBusinessChildren = new DeviceBusinessChildren();
        deviceBusinessChildren.setId(id);
        deviceBusinessChildren.setName(jsonParam.getStr("name"));
        deviceBusinessChildren.setNumber(jsonParam.getStr("number"));
        deviceBusinessChildren.setTransDeviceCode(jsonParam.getStr("transDeviceCode"));
        deviceBusinessChildren.setDeviceType(jsonParam.getStr("deviceType"));
        deviceBusinessChildren.setInstalltime(jsonParam.getStr("installTime"));
        deviceBusinessChildren.setLat(deviceBusiness.getLat());
        deviceBusinessChildren.setLon(deviceBusiness.getLon());
        deviceBusinessChildren.setCreatetime(new Date());
        deviceBusinessChildren.setCurrentstate("1");
        deviceBusinessChildren.setNormalUpdateTime(DateUtil.now());
        deviceBusinessChildrenMapper.insert(deviceBusinessChildren);
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 删除子设备
     * @Date Created in 10:00 2023/5/11
     * @Param [jsonParam]
     */

    public RespEntity deviceChildrenDel(JSONObject jsonParam) throws Exception {

        if (StrUtil.isBlank(jsonParam.getStr("id"))){
            return RespEntity.fail("id不能为空");
        }
        deviceBusinessChildrenMapper.deleteById(jsonParam.getStr("id"));
        return RespEntity.success();
    }

    public static String execCurl(String[] cmds) {

        ProcessBuilder process = new ProcessBuilder(cmds);

        Process p;

        try {

            p = process.start();

            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

            StringBuilder builder = new StringBuilder();

            String line = null;

            while ((line = reader.readLine()) != null) {

                builder.append(line);

                builder.append(System.getProperty("line.separator"));

            }

            return builder.toString();

        } catch (IOException e) {

            System.out.print("error");

            e.printStackTrace();

        }

        return null;

    }

    /**
     * @Author YangYu
     * @Description 获取水柱箱体数据
     * @Date Created in 13:54 2023/7/11
     * @Param [jsonParam]
     */

    public RespEntity getWaterColumnBoxData(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        if (StrUtil.isBlank(jsonParam.getStr("number"))){
            return RespEntity.fail("number不能为空");
        }
        WaterColumnBoxData waterColumnBoxData = waterColumnBoxDataMapper.selectOne(new QueryWrapper<WaterColumnBoxData>().eq("number",jsonParam.getStr("number")));
        return RespEntity.success(waterColumnBoxData);
    }
    /**
     * @Author YangYu
     * @Description 水柱箱体历史数据(分页)
     * @Date Created in 14:50 2023/3/2
     * @Param [jsonParam]
     */

    public RespEntity waterColumnBoxDataLogList(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        Page<WaterColumnBoxDataLog> page = new Page<>(jsonParam.getInt("page"),jsonParam.getInt("limit"));
        IPage<WaterColumnBoxDataLog> iPage =  waterColumnBoxDataLogMapper.waterColumnBoxDataLogPageList(page, jsonParam);
        List<WaterColumnBoxDataLog> records = iPage.getRecords();
        Map<String, Object> data = new HashMap<>();
        data.put("totalSize", iPage.getTotal());
        data.put("pages", iPage.getPages());
        data.put("pageSize", jsonParam.getInt("limit"));
        data.put("Items",records);
        data.put("currentPage",jsonParam.getInt("page"));
        data.put("currentSize",jsonParam.getInt("limit"));
        return RespEntity.success(data);
    }
    /**
     * @Author YangYu
     * @Description 水柱箱体下发指令
     * @Date Created in 15:13 2023/7/11
     * @Param [jsonParam]
     */

    public RespEntity setWaterColumnBoxData(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        if (StrUtil.isBlank(jsonParam.getStr("number"))){
            return RespEntity.fail("number不能为空");
        }
        DeviceBusiness deviceBusiness = deviceBusinessMapper.selectOne(new QueryWrapper<DeviceBusiness>().eq("number",jsonParam.getStr("number")));
        if (StrUtil.isBlank(deviceBusiness.getDownDevId()) || deviceBusiness.getDownDevId().equals("")){
            return RespEntity.fail("下发指令设备ID还未更新，请设备上电连接!");
        }
        //数据域
        String data = "0000000000000000000000";
        if (jsonParam.containsKey("data")){
            if (!jsonParam.getStr("instructions").equals("08")){
                //计算下发的数据
                double d = jsonParam.getDouble("data");
                BigDecimal bigDecimal = BigDecimal.valueOf(d).multiply(BigDecimal.valueOf(100));
                Integer integer = bigDecimal.intValue();
                data = hex10To16s(integer)+"000000000000000000";
            }else {
                if (jsonParam.getInt("data") == 1){
                    data = "0001000000000000000000";
                }else if (jsonParam.getInt("data") == 2){
                    data = "0002000000000000000000";
                }else {
                    data = "0003000000000000000000";
                }
            }
        }
        String code = "AAAA55AA"+deviceBusiness.getNumber()+"02"+jsonParam.getStr("instructions")+data;
        //crc计算
        String crc = getCrcJ(code);
        code = code+crc+"CCCC";
        jsonParam.put("dev_id",deviceBusiness.getDownDevId());
        jsonParam.put("code",code);
        rest(jsonParam, "tcp_server_cmd", "tcp_server_cmd", "tcp", "POST");

        //更新下发指令的设备ID
        UpdateWrapper<WaterColumnBoxData> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("number",jsonParam.getStr("number"));
        WaterColumnBoxData waterColumnBoxData = new WaterColumnBoxData();
        if (jsonParam.getStr("instructions").equals("01")){
            return RespEntity.success();
        }else if (jsonParam.getStr("instructions").equals("02")){
            waterColumnBoxData.setUpperLimitAlarmSettingValues(jsonParam.getDouble("data"));
        }else if (jsonParam.getStr("instructions").equals("03")){
            waterColumnBoxData.setUpperLimitAlarmSettingValue(jsonParam.getDouble("data"));
        }else if (jsonParam.getStr("instructions").equals("04")){
            waterColumnBoxData.setLowerLimitAlarmSetPoint(jsonParam.getDouble("data"));
        }else if (jsonParam.getStr("instructions").equals("05")){
            waterColumnBoxData.setLowerLimitAlarmSetPoints(jsonParam.getDouble("data"));
        }else if (jsonParam.getStr("instructions").equals("06")){
            waterColumnBoxData.setStartValue(jsonParam.getDouble("data"));
        }else if (jsonParam.getStr("instructions").equals("07")){
            waterColumnBoxData.setStopValue(jsonParam.getDouble("data"));
        }else if (jsonParam.getStr("instructions").equals("08")){
            waterColumnBoxData.setManualAutomaticState(jsonParam.getInt("data"));
        }
        waterColumnBoxDataMapper.update(waterColumnBoxData,updateWrapper);
        return RespEntity.success();
    }


    /**
     * @Author YangYu
     * @Description sos通讯录新增、编辑
     * @Date Created in 09:32 2023/7/27
     * @Param [jsonParam]
     */

    public RespEntity addOrUpdateBook(JSONObject jsonParam) throws Exception{
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");

        DeviceBusiness deviceBusiness = deviceBusinessMapper.selectOne(new QueryWrapper<DeviceBusiness>().eq("number",jsonParam.getStr("number")));
        if (deviceBusiness == null){
            return RespEntity.fail("设备不存在!");
        }

        String uuid = "";
        if (jsonParam.containsKey("id")){
            uuid = jsonParam.getStr("id");
            sosAddressBookMapper.deleteById(uuid);
        }else {
            uuid = UUID.randomUUID().toString();
        }
        SosAddressBook sosAddressBook = new SosAddressBook();
        sosAddressBook.setId(uuid);
        sosAddressBook.setNumber(jsonParam.getStr("number"));
        sosAddressBook.setName(jsonParam.getStr("name"));
        sosAddressBook.setPhone(jsonParam.getStr("phone"));
        sosAddressBook.setPressKey(jsonParam.getInt("pressKey"));
        sosAddressBook.setType(jsonParam.getInt("type"));
        sosAddressBookMapper.insert(sosAddressBook);
        //异步下发亲情号、紧急号
        asyncService.addBook(jsonParam.getStr("number"),jsonParam.getInt("type"),jsonParam.getInt("pressKey"),jsonParam.getStr("phone"),deviceBusiness.getProductId(),jsonParam.getStr("name"));
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description sos通讯录列表
     * @Date Created in 14:17 2023/7/31
     * @Param [jsonParam]
     */

    public RespEntity sosAddressBookList(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        List<SosAddressBook> sosAddressBookList = sosAddressBookMapper.selectList(new QueryWrapper<SosAddressBook>().eq("number",jsonParam.getStr("number")).eq("type",jsonParam.getInt("type")));
        return RespEntity.success(sosAddressBookList);
    }



    /**
     * @Author YangYu
     * @Description 设置视频设备播放时间
     * @Date Created in 11:01 2023/12/19
     * @Param [jsonParam]
     */

    public RespEntity setVideoPlayTime(JSONObject jsonParam){
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        if (StrUtil.isBlank(jsonParam.getStr("number"))){
            return RespEntity.fail("设备编号不能为空!");
        }
        DeviceVideoPlayTime deviceVideoPlayTime = jsonParam.toBean(DeviceVideoPlayTime.class);
        deviceVideoPlayTime.setPlayTime(jsonParam.getDouble("playTime") * 60 * 60);
        //先删除防止重复
        deviceVideoPlayTimeMapper.delete(new QueryWrapper<DeviceVideoPlayTime>().eq("number",deviceVideoPlayTime.getNumber()));
        deviceVideoPlayTimeMapper.insert(deviceVideoPlayTime);
        return RespEntity.success();
    }


    /**
     * @Author YangYu
     * @Description 获取视频设备播放时间
     * @Date Created in 11:01 2023/12/19
     * @Param [jsonParam]
     */

    public RespEntity getVideoPlayTime(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        if (StrUtil.isBlank(jsonParam.getStr("number"))){
            return RespEntity.fail("设备编号不能为空!");
        }
        DeviceVideoPlayTime deviceVideoPlayTime = deviceVideoPlayTimeMapper.selectOne(new QueryWrapper<DeviceVideoPlayTime>().eq("number",jsonParam.getStr("number")));
        if (deviceVideoPlayTime != null && deviceVideoPlayTime.getPlayTime() != 0){
            //保留两位小数
            DecimalFormat df = new DecimalFormat("#.##");
            deviceVideoPlayTime.setPlayTime(new Double(df.format(deviceVideoPlayTime.getPlayTime()/60/60)));
            return RespEntity.success(deviceVideoPlayTime);
        }else {
            return RespEntity.fail("该设备流量已用尽,请联系管理员进行充值!");
        }
    }


    /**
     * @Author YangYu
     * @Description 更新视频设备播放时间
     * @Date Created in 11:01 2023/12/19
     * @Param [jsonParam]
     */

    public RespEntity updateVideoPlayTime(JSONObject jsonParam) throws ParseException {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        if (StrUtil.isBlank(jsonParam.getStr("number"))){
            return RespEntity.fail("设备编号不能为空!");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 开始时间
        long startTime = sdf.parse(jsonParam.getStr("startTime")).getTime()/1000;
        // 结束时间
        long endTime = sdf.parse(jsonParam.getStr("endTime")).getTime()/1000;
        // 用时
        long count = endTime-startTime;
        DeviceVideoPlayTime deviceVideoPlayTime = deviceVideoPlayTimeMapper.selectOne(new QueryWrapper<DeviceVideoPlayTime>().eq("number",jsonParam.getStr("number")));

        deviceVideoPlayTime.setPlayTime(deviceVideoPlayTime.getPlayTime() - count);
        deviceVideoPlayTimeMapper.update(deviceVideoPlayTime,new QueryWrapper<DeviceVideoPlayTime>().eq("number",jsonParam.getStr("number")));
        return RespEntity.success();
    }
    /**
     * @Author YangYu
     * @Description 十进制转十六进制字符串
     * @Date Created in 10:48 2021/12/15
     * @Param [value]
     */

    public static String hex10To16s(Integer value) {
        String hex = Integer.toHexString(value);
        if (hex.length() == 1) {
            hex = "000" + hex;
        }else if (hex.length() == 2){
            hex = "00" + hex;
        }else if (hex.length() == 3){
            hex = "0" + hex;
        }
        return hex;
    }
    /**
     * @Author YangYu
     * @Description 京电云设备计算crc
     * @Date Created in 15:51 2023/7/12
     * @Param [hex]
     */

    public static String getCrcJ(String hex){
        int j = 0;
        //每两位截取并转成十进制
        for (int i = 0; i < hex.length(); i += 2) {
            String output = hex.substring(i, (i + 2));
            j = j+Integer.parseInt(output,16);
        }
        return hex10To16s(j).substring(2,4);
    }


    /**
     * @Author YangYu
     * @Description 手动更新设备状态
     * @Date Created in 10:18 2024/1/10
     * @Param [jsonParam]
     */

    public RespEntity updateDeviceState(JSONObject jsonParam){
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        if (StrUtil.isNotBlank(jsonParam.getStr("number")) && StrUtil.isNotBlank(jsonParam.getStr("state"))){
            DeviceBusiness deviceBusiness = deviceBusinessMapper.selectOne(new QueryWrapper<DeviceBusiness>().eq("number",jsonParam.getStr("number")));
            deviceBusiness.setCurrentstate(jsonParam.getStr("state"));
            deviceBusiness.setNormalUpdateTime(DateUtil.now());
            deviceBusinessMapper.updateById(deviceBusiness);
            return RespEntity.success();
        }else {
            return RespEntity.fail("参数不能为空!");
        }
    }

    /**
     * @Author YangYu
     * @Description 气体灭火系统数据
     * @Date Created in 11:15 2024/4/3
     * @Param [jsonParam]
     */

    public RespEntity getGasFireExtinguishingData(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        //com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        //if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        //if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        //String homeId = token.getString("home_id");
        //String userType = token.getString("user_type");
        GasFireExtinguishingData gasFireExtinguishingData = gasFireExtinguishingDataMapper.selectOne(new QueryWrapper<GasFireExtinguishingData>().eq("number",jsonParam.getStr("number")));
        return RespEntity.success(gasFireExtinguishingData);
    }

    /**
     * @Author YangYu
     * @Description 物联网平台下发指令
     * @Date Created in 15:05 2024/12/17
     * @Param [jsonParam]
     */

    public RespEntity iotPost(JSONObject jsonParam){
        DeviceBusiness deviceBusiness = deviceBusinessMapper.selectById(jsonParam.getStr("id"));
        if (deviceBusiness == null){
            return RespEntity.fail("设备不存在");
        }
        if (deviceBusiness.getDeviceClassify().equals("7")){
            String number = "";
            String code = "";
            String state = "";
            if (deviceBusiness.getIsChildren() == 1){
                number = deviceBusiness.getNumber().split(deviceBusiness.getTransDeviceCode())[1];
                code = "B2";
                state = jsonParam.getStr("state");
            }else {
                number = deviceBusiness.getNumber();
                if (jsonParam.getStr("state").equals("1")){
                    code = "B3";
                    state = "0";
                }else if (jsonParam.getStr("state").equals("2")){
                    code = "B4";
                    state = "0";
                }
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("serialNumber",number);
            jsonObject.put("productId",148);
            JSONObject params = new JSONObject();
            params.put(code,state);
            jsonObject.put("params",params);
            restIotToken(jsonObject,"iotPost","post","iot_post","eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjkxZGQ0YzEzLTQzMzItNDRkYy04MGU4LTdlNWE5YmFhZDY2NSJ9.0MiTNYXmt5cjxZR7zbHN_mJEVvKH0uHeFCsPl0y5-3qDnxTJzk6UBdCY552d7g3INOgdAW0R_cPTjJD2j0PqeQ","POST");
        }
        return RespEntity.success();
    }

}
